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?

Goのif文とエラーハンドリングを理解する

0
Posted at

1. はじめに

この記事でわかること:

  • Goの if / else if / else の基本
  • if 文内での変数宣言
  • スコープの考え方
  • if err != nil によるエラーハンドリング

2. if / else if / else の基本

まずは、最も基本的な if 文です。

a := 1

if a == 2 {
	fmt.Println("2だ")
} else if a == 1 {
	fmt.Println("1だ")
} else {
	fmt.Println("それ以外")
}

実行結果

1だ

ポイント

  • 条件式は bool 型のみ
  • () は不要(書くとエラー)
  • {} は必須
// if (a == 1) { } // コンパイルエラー

3. if 文内での変数宣言

Goの if では、条件の前で変数を宣言できます。

if b := 100; b == 100 {
	fmt.Println("100だ")
}

実行結果

100だ

ポイント

  • bif 文の中だけで有効
  • if を抜けると参照できない
// fmt.Println(b) // コンパイルエラー

4. スコープの挙動に注意する

次のコードは、少しややこしいですがとても重要です。

x := 5

if x := 2; true {
	fmt.Println(x) // 2
}

fmt.Println(x) // 5

実行結果

2
5

何が起きているか?

  • if x := 2新しい x を定義している
  • if の中と外では 別の変数

5. Goのエラーハンドリング

Goでは、例外(try-catch)の代わりに戻り値として error を返す決まりがあります。

var s string = "100"
i, err := strconv.Atoi(s)

if err != nil {
	fmt.Println(err)
}

fmt.Printf("%T %v\n", i, i)

実行結果

int 100

ポイント

  • Atoi(int, error) を返す
  • エラーがなければ err == nil
  • エラーがあれば 必ずチェックする

6. if とエラーハンドリングの定番パターン

実務で最もよく見るのがこの形です。

if i, err := strconv.Atoi(s); err != nil {
	fmt.Println(err)
} else {
	fmt.Println(i)
}

メリット

  • 変数のスコープが狭くなる
  • エラー処理と成功処理がまとまる
  • Goらしい読みやすさ

7. Goのif文のまとめ

  • 条件式は bool のみ
  • () は不要
  • {} は必須
  • if 文内で変数宣言ができる
  • スコープはブロック単位
  • if err != nil はGoの基本形

参考

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?