Go言語基本文法(2) ~for, if, switch, defer~

for

package main

import "fmt"

func main() {
    sum1 := 0
    for i := 0; i < 10; i++ {
        sum1 += i
    }
    fmt.Println(sum1)
    // 45

    sum2 := 1
    for sum2 < 1000 {
        sum2 += sum2
    }
    fmt.Println(sum2)
    // 1024
}

無限ループ

package main

func main() {
    for {
    }
}

if

package main

import (
    "fmt"
    "math"
)

func sqrt(x float64) string {
    if x < 0 {
        return sqrt(-x) + "i"
    }
    return fmt.Sprint(math.Sqrt(x))
}

func main() {
    fmt.Println(sqrt(2), sqrt(-4))
    // 1.4142135623730951 2i
}

if文の最初で変数を宣言することもできる。

package main

import (
    "fmt"
    "math"
)

func pow(x, n, lim float64) float64 {
    // vを宣言
    if v := math.Pow(x, n); v < lim {
        return v
    }
    // ここまでvは有効
    return lim
}

func main() {
    fmt.Println(pow(3, 2, 10))
    // 9
    fmt.Println(pow(3, 4, 10))
    // 10
}
package main

import (
    "fmt"
    "math"
)

func pow(x, n, lim float64) float64 {
    if v := math.Pow(x, n); v < lim {
        return v
    } else {
        fmt.Printf("%g >= %g\n", v, lim)
    }
    // can't use v here, though
    return lim
}

func main() {
    fmt.Println(
        pow(3, 2, 10),
        pow(3, 3, 20),
    )
    // 27 >= 20
    // 9 20
    // 先に2つのpowが実行されてから、main()内のPrintlnが実行される
}

switch

package main

import (
    "fmt"
)

func main() {
    switch x := 1; x {
    case 0:
        fmt.Println(0)
    case 1:
        fmt.Println(1)
    default:
        fmt.Println(-1)
    }
    // 1
}
package main

import (
    "fmt"
)

func main() {
    x := 3
    switch {
    case x < 2:
        fmt.Println(x, "< 2")
    case x < 5:
        fmt.Println(x, "< 5")
    default:
        fmt.Println(x, ">= 5")
    }
    // 3 < 5
}

fallthrough

goでは、switchの各caseが終わると自動的にbreakしてしまうが、breakせずに次のcaseに進みたい場合はfallthroughを使う

func main() {
    n := 3
    switch n {
    case 3:
        n = n - 1
        fallthrough
    case 2:
        n = n - 1
        fallthrough
    case 1:
        n = n - 1
        fmt.Println(n) // 0
    }
}

defer

package main

import "fmt"

func main() {
    // mainがreturnした後に実行される
    defer fmt.Println("world")

    fmt.Println("hello")
    // hello
    // world
}
package main

import "fmt"

func main() {
    fmt.Println("counting")

    for i := 0; i < 10; i++ {
        defer fmt.Println(i)
    }

    fmt.Println("done")
 
    // counting
    // done
    // 9
    // 8
    // 7
    // 6
    // 5
    // 4
    // 3
    // 2
    // 1
 
    // 実行順はLIFO
}

参考

A Tour of Go