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?

More than 3 years have passed since last update.

Go 言語仕様3(エラーハンドリング、for文、型アサーション、switch文、型スイッチ)

Last updated at Posted at 2021-02-13

概要

複数の言語を扱っていると仕様が混ざるので、まとめておく。

前回:
Go 言語仕様2(関数)

内容

  • エラーハンドリング
  • for文
  • 型アサーション
  • switch文
  • 型スイッチ

エラーハンドリング

戻り値のエラーを受け取って、エラーがあれば処理する。

func main() {
	var s string = "Golang"

	// エラーの場合は、2つ目の戻り値にエラー内容が入る
	i, err := strconv.Atoi(s)
	if err != nil {
		panic(err) // panic: strconv.Atoi: parsing "test": invalid syntax
	}

	fmt.Println(i)
}

for文

  • Go言語のループ処理はfor文のみ
func main() {
	for i := 0; i < 10; i++ {
		if i == 4 {
			continue
		}

		if i == 8 {
			break
		}

		fmt.Println(i) // 0 1 2 3 5 6 7
	}

	// 配列の要素数分ループさせる
	arr := [4]int{1, 2, 3, 4}
	for i := 0; i < len(arr); i++ {
		fmt.Println(arr[i]) // 1 2 3 4
	}
}
ラベル付きfor
// 多重ループの内側で全ループを終了させたい場合、ラベルを使う
func main() {
Loop:
	for {
		for {
			for {
				fmt.Println("start")
				break Loop
			}
		}
	}
	fmt.Println("end")
}
// foreachのようなループは、rangeを使う
m := map[string]int{"cat": 10, "coyote": 20, "giraffe": 30}
for k, v := range m {
	fmt.Println(k, v) // cat 10 coyote 20 giraffe 30
}

// valueのみほしい場合は、_を使う
m2 := map[string]int{"cat": 10, "coyote": 20, "giraffe": 30}
for _, v := range m2 {
	fmt.Println(v) // 10 20 30
}

型アサーション

interface{}型はすべての型と互換性があるが、
interface{}型で受け取った値は、元の型として処理を実行できない。
そこで、型アサーションをすることで、元の型として扱えるようにする。

型アサーション
// 型アサーションをしないままだと、元の型として値を扱えない
var f interface{} = "Hello"
fmt.Println(ff + "World") // invalid operation: ff + "World" (mismatched types interface {} and string)

/*
  stringに型アサーションする
  value, ok := 変数.(型)
  valueで値を受け取り、okでは型アサーションの実行結果をboolで受け取る。
*/
var ff interface{} = "Hello"
value, ok := ff.(string)
if ok {
	fmt.Println(value + "World") // HelloWorld
} else {
	// エラー処理
}

switch文

Go言語switch文の特徴は以下。

  • caseに複数の値を指定できる。
  • caseの条件に入り処理が実行されると自動的にbreakされるため、breakの記述が必要ない。
  • fallthroughと記述することで、次のcase文を実行できる。
switch文
func main() {
	var s string = "Golang"
	// switchで評価する値とcaseの型は合わせる必要がある
	switch s {
	case "Java":
		fmt.Println("Java")
	case "Pyhon", "Golang":
		fmt.Println("Python or Golang")
		// fallthroughを入れることで、breakされずに次のcaseを実行する
		fallthrough
	default:
		fmt.Println("default")
	}
}

型スイッチ

型アサーションとswitch文の合せ技。
受け取るパラメータの型が決まっていないときなどに有効。

型スイッチ
func checkTypes(f interface{}) {
	if f == nil {
		return
	}

	switch v := f.(type) {
	case int:
		fmt.Println("type: int ", v)
	case string:
		fmt.Println("type: string ", v)
	case float64:
		fmt.Println("type: float64 ", v)
	case bool:
		fmt.Println("type: bool ", v)
	default:
		fmt.Println("type: unknown ", v)
	}
}

func main() {
	checkTypes(3)
	checkTypes("Golang")
	checkTypes(true)
}

次回

Go 言語仕様4(defer, panic, recover)

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?