Go の if と else で分岐させるのは簡単です。
if
else
package main
import "fmt"
func main() {
基本的な例を示します。
if 7%2 == 0 { fmt.Println("7 is even") } else { fmt.Println("7 is odd") }
else のない if ステートメントを使用できます。
if 8%4 == 0 { fmt.Println("8 is divisible by 4") }
&& や || などの論理演算子は条件としてよく使用されます。
&&
||
if 8%2 == 0 || 7%2 == 0 { fmt.Println("either 8 or 7 are even") }
分岐条件の前にステートメントを置くことができます。ここで宣言された変数は、現在の分岐とそれ以降のすべての分岐で使用できます。
if num := 9; num < 0 { fmt.Println(num, "is negative") } else if num < 10 { fmt.Println(num, "has 1 digit") } else { fmt.Println(num, "has multiple digits") } }
Go では条件に括弧は必要ありませんが、中括弧は必要であることに注意してください。
$ go run if-else.go 7 is odd 8 is divisible by 4 either 8 or 7 are even 9 has 1 digit
Go には ternary if はないので、基本的な条件の場合でも完全な if ステートメントを使用する必要があります。
次の例: Switch。
by Mark McGranaghan と Eli Bendersky | ソース | ライセンス