non-boolean condition in if statement の原因と直し方
C言語やJavaScriptと違い、Goのif文の条件式には真偽値(bool)しか書けません。0や1のような整数をそのまま条件に置くとコンパイルエラーになります。
エラーメッセージの読み方
./main.go:7:5: non-boolean condition in if statement
./main.go- ファイル名
7- 行番号
5- 列番号
non-boolean condition in if statement- 詳細メッセージ — 何が問題だったか
このエラーが出る典型パターン
パターン1
1 package main 2 3 import "fmt" 4 5 func main() { 6 x := 1 7 if x { ^ 8 fmt.Println("yes") 9 } 10 }
./main.go:7:5: non-boolean condition in if statement
C言語やJavaScriptと違い、Goのif文の条件式は真偽値でなければなりません。整数xをそのまま置くことはできません。
直し方: x を x != 0 にします。
広告
広告スロット(未設定)
パターン2
1 package main 2 3 import "fmt" 4 5 func main() { 6 n := 0 7 if n { ^ 8 fmt.Println("yes") 9 } 10 }
./main.go:7:5: non-boolean condition in if statement
nがゼロかどうかを条件にしたい場合でも、比較演算子で明示的にbool値を作る必要があります。
直し方: n を n > 0 にします。
パターン3
1 package main 2 3 import "fmt" 4 5 func main() { 6 flag := 1 7 if flag { ^ 8 fmt.Println("yes") 9 } 10 }
./main.go:7:5: non-boolean condition in if statement
他の言語で「フラグが立っている」を意味する1をそのまま条件式に書く癖は、Goでは通用しません。
直し方: flag を flag == 1 にします。
パターン4
1 package main 2 3 import "fmt" 4 5 func main() { 6 count := 3 7 if count { ^ 8 fmt.Println("yes") 9 } 10 }
./main.go:7:5: non-boolean condition in if statement
countが0でないことを判定したいなら、count >= 1やcount != 0のように明示する必要があります。
直し方: count を count >= 1 にします。
パターン5
1 package main 2 3 import "fmt" 4 5 func main() { 6 code := 0 7 if code { ^ 8 fmt.Println("yes") 9 } 10 }
./main.go:7:5: non-boolean condition in if statement
エラーコードが0以外かを判定したい場合も、int値をそのまま条件式に書くことはできません。
直し方: code を code != 0 にします。
よくある誤解
「0はfalse、0以外はtrueとして扱われるはず」という思い込みは誤りです。Goには数値からboolへの暗黙変換が無いため、比較演算子を使って明示的にbool値を作る必要があります。
まとめ
non-boolean condition in if statementは初級でつまずきやすい項目です。上の5パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。