Go 沒有 truthy falsy,判斷式只吃 bool

把非 bool 的值放進判斷式是編譯錯誤,不是執行期才炸。Go 不替你決定「什麼算真」。

x := 10
if x { }          // ✗ non-boolean condition in if statement
if x != 0 { }     // ✓ 必須自己寫出比較
 
s := ""
if s { }          // ✗
if s == "" { }    // ✓
 
var p *int
if p { }          // ✗
if p == nil { }   // ✓

for 的條件、switch 的 case、以及 && / || / ! 全都一樣,只接受 bool

這是不做隱式轉換這條原則在控制流程上的延伸,帶來三個具體差異:

  • 沒有 JS 那種 0 / "" / [] / {} 哪個是 falsy 要背的表
  • 不能寫 if len(arr) 的簡寫,得寫 if len(arr) > 0
  • if err != nil 之所以是 Go 的招牌長相,就是因為不能寫 if err

唯一看起來像例外的是底層型別為 bool 的自訂型別:

type Enabled bool
var e Enabled
if e { }          // ✓ 底層型別就是 bool,不是轉換

同理,comma okok 能直接寫 if ok,是因為它本來就是 bool

相關:Go 的 if 可以先宣告變數且作用域涵蓋 elseGo 的 switch 預設不 fallthrough