LoginSignup
1
0

【Go言語】制御構文

Last updated at Posted at 2023-12-07

制御構文とは

プログラムの流れを制御するための重要な構成要素。
Go言語にはif,for,switchなど基本的な制御構文がある。

if文

ifは条件節がブール型である必要がある

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	rand.Seed(time.Now().UnixNano())
	// 0か1をランダムに生成
	x := rand.Intn(2)

	if x == 0 {
		fmt.Println("x=0")
	} else {
		fmt.Println("x=1")
	}

}

Goではfalsyという概念がないので以下のコードはビルドエラーとなる

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	rand.Seed(time.Now().UnixNano())
	// 0か1をランダムに生成
	x := rand.Intn(2)

	// エラーになる
	// non-boolean condition in if statement
	if x {
		fmt.Println("x=1")
	}
}

変数宣言とセットで利用する方法もある
宣言した変数はifブロック内でしか利用できないので注意が必要

package main

import (
	"fmt"
)

func main() {
	// 例として、キャッシュされたデータを表すマップを定義
	cache := map[string]string{
		"key1": "value1",
		"key2": "value2",
	}

	// ユーザーの入力を模倣する変数
	input := "key1"

	// if文でデータ取得とチェックを同時に行う
	if result, ok := cache[input]; ok {
		fmt.Println("Cached value:", result)
	} else {
		fmt.Println("Value not found in cache.")
	}
}

for文

rangeを利用してスライスやマップの全要素を取り出すときに使用することが多い

package main

import "fmt"

func main() {
	abc := []string{"a", "b", "c"}
	for i, s := range abc {
		fmt.Println(i, s) // インデックス 値
	}
}

変数を1つだけ書くとスライスはインデックス、マップはキーのみを返す。
また、使用しない変数をブランク識別子_を使うことで未定義エラーにならない

package main

import "fmt"

func main() {
	abc := []string{"a", "b", "c"}
	for i := range abc {
		fmt.Println(i) // インデックス
	}

	for _, s := range abc {
		fmt.Println(s) // 値
	}
}

breakでロールを強制終了したり、continueでループの先頭に戻ったりすることができる

package main

import "fmt"

func main() {
	var abc []rune
	for ch := 'a'; ch <= 'z'; ch++ {
		if ch == 'c' {
			continue
		} else if ch == 'f' {
			break
		}

		abc = append(abc, ch)
	}

	fmt.Println(string(abc)) // abde

}

switch

if ... else ifを簡単に書くことができる

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	rand.Seed(time.Now().UnixNano())
	x := rand.Intn(5)

	switch x {
	case 0:
		fmt.Println("x=0")
	case 1:
		fmt.Println("x=1")
	case 2:
		fmt.Println("x=2")
	default:
		fmt.Println("x>2")
	}
}

参考

1
0
1

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