0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

for、if、switch、defer

Last updated at Posted at 2024-12-16

はじめに

A Tour of Goについて勉強になった箇所をまとめる。

For

初期化、条件式、後処理を括る括弧 ( ) はない。中括弧 { } は必要。

package main

import "fmt"

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

初期化と後処理の記述は任意。

package main

import "fmt"

func main() {
	sum := 1
	for ; sum < 1000; {
		sum += sum
	}
	fmt.Println(sum)
}

セミコロンの省略可能。

package main

import "fmt"

func main() {
	sum := 1
	for sum < 1000 {
		sum += sum
	}
	fmt.Println(sum)
}

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

条件の前に、評価するための簡単なステートメントを書ける。

package main

import (
	"fmt"
	"math"
)

func pow(x, n, lim float64) float64 {
	if v := math.Pow(x, n); v < lim {
		return v
	}
	return lim
}

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

ifで宣言された変数は、elseでも使える。

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

Switch

選択されたcaseだけ実行しその後の全ての case は実行されない。 PHP等の breakが Go だと自動的に実行される。

またswitchcaseは定数である必要がなく、 関係する値は整数である必要はない。

package main

import (
	"fmt"
	"runtime"
)

func main() {
	fmt.Print("Go runs on ")
	switch os := runtime.GOOS; os {
	case "darwin":
		fmt.Println("OS X.")
	case "linux":
		fmt.Println("Linux.")
	default:
		// freebsd, openbsd,
		// plan9, windows...
		fmt.Printf("%s.\n", os)
	}
}
// Go runs on Linux.

条件のないswitchは、switch trueと書くことと同じ。

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
    switch {
    case t.Hour() < 12:
        fmt.Println("Good morning!")
    case t.Hour() < 17:
        fmt.Println("Good afternoon.")
    default:
        fmt.Println("Good evening.")
    }
}

次のcaseブロックを続けて実行したい場合は、明示的にfallthroughをキーワードを使う。

switch num := 3; num {
case 1:
    println("One")
case 2:
    println("Two")
case 3:
    println("Three")
    fallthrough
case 4:
    println("Four")
default:
    println("Unknown number")
}

Defer

deferへ渡した関数の実行を、呼び出し元の関数の終わり(returnする)まで遅延させる。
deferへ渡した関数の引数はすぐに評価されるが、その関数自体は呼び出し元の関数がreturnするまで実行されない。

package main

import "fmt"

func main() {
	defer fmt.Println("world")

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

deferへ渡した関数が複数ある場合、その呼び出しはスタックされる。 呼び出し元の関数がreturnするとき、 deferへ渡した関数はLIFO(last-in-first-out)の順で実行される。

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
// 0
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?