# 布林

本頁介紹只有 `true` 與 `false` 兩種值的 `bool` 型別、邏輯運算子的短路求值，以及為什麼 Go 不讓布林和數字互相轉換。

## bool 型別

布林（boolean）型別 `bool` 只有兩個值：`true`（真）與 `false`（假），零值是 `false`。它是 `if`、`for` 條件唯一接受的型別。

### 比較運算產生布林值

比較運算子的結果都是 `bool`，可以直接存進變數、當函式回傳值，讓條件更好讀：

| 運算子 | 意思 |
| --- | --- |
| `==`、`!=` | 等於、不等於 |
| `<`、`<=`、`>`、`>=` | 小於、小於等於、大於、大於等於 |

```go
package main

import "fmt"

func isAdult(age int) bool {
	return age >= 18
}

func main() {
	var ready bool
	fmt.Println("零值:", ready)

	age := 20
	adult := isAdult(age)
	sameName := "Go" == "go"
	fmt.Println(adult, sameName, 3 != 4)
	fmt.Printf("%t %v %T\n", adult, sameName, adult)

	if adult {
		fmt.Println("可以投票")
	}
}
```

輸出：

```text
零值: false
true false true
true false bool
可以投票
```

`%t` 是布林專用的格式動詞。條件已經是 `bool` 時直接寫 `if adult`，不要寫成 `if adult == true`。

### 邏輯運算子

三個邏輯運算子用來組合布林值：

| 運算子 | 名稱 | 結果為 `true` 的條件 |
| --- | --- | --- |
| `&&` | AND（且） | 兩邊都是 `true` |
| `\|\|` | OR（或） | 至少一邊是 `true` |
| `!` | NOT（非） | 原本是 `false` |

優先順序是 `!` 最高、`&&` 次之、`||` 最低，所以 `a || b && c` 等於 `a || (b && c)`。混用時加括號最清楚：

```go
package main

import "fmt"

func main() {
	hasTicket := true
	isVIP := false
	age := 15

	fmt.Println(hasTicket && age >= 18)
	fmt.Println(hasTicket || isVIP)
	fmt.Println(!isVIP)

	fmt.Println(isVIP || hasTicket && age >= 18)
	fmt.Println((isVIP || hasTicket) && age >= 18)

	for _, a := range []bool{false, true} {
		for _, b := range []bool{false, true} {
			fmt.Printf("%-5t %-5t | && %-5t || %t\n", a, b, a && b, a || b)
		}
	}
}
```

輸出：

```text
false
true
true
false
false
false false | && false || false
false true  | && false || true
true  false | && false || true
true  true  | && true  || true
```

## 短路求值

`&&` 與 `||` 由左往右計算，而且一旦結果確定就停下來，不再計算右邊，這叫短路求值（short-circuit evaluation）：

- `a && b`：`a` 是 `false` 時結果必定是 `false`，不計算 `b`
- `a || b`：`a` 是 `true` 時結果必定是 `true`，不計算 `b`

### 右邊不一定會執行

如果右邊是函式呼叫，短路時函式根本不會被呼叫。下面用會印字的函式觀察執行順序：

```go
package main

import "fmt"

func check(name string, result bool) bool {
	fmt.Println("  計算", name)
	return result
}

func main() {
	fmt.Println("false && ...")
	fmt.Println(check("左", false) && check("右", true))

	fmt.Println("true || ...")
	fmt.Println(check("左", true) || check("右", false))

	fmt.Println("true && ...")
	fmt.Println(check("左", true) && check("右", true))
}
```

輸出：

```text
false && ...
  計算 左
false
true || ...
  計算 左
true
true && ...
  計算 左
  計算 右
true
```

前兩個例子都沒有「計算 右」，只有最後一個左邊為 `true` 的 `&&` 才需要看右邊。所以不要把「一定要執行」的動作放在 `&&`、`||` 的右邊。

### 用短路保護後面的運算

短路最實用的地方是「先檢查、再存取」：左邊確認安全，右邊才去做可能出錯的事。例如先確認指標不是 `nil`、索引沒有越界、除數不是 0：

```go
package main

import "fmt"

type User struct {
	Name string
}

func main() {
	var u *User
	if u != nil && u.Name == "admin" {
		fmt.Println("管理員")
	} else {
		fmt.Println("不是管理員或沒有使用者")
	}

	nums := []int{10, 20}
	i := 5
	if i < len(nums) && nums[i] > 0 {
		fmt.Println("正數")
	} else {
		fmt.Println("索引超出範圍")
	}

	total, count := 100, 0
	if count != 0 && total/count > 10 {
		fmt.Println("平均大於 10")
	} else {
		fmt.Println("沒有資料")
	}
}
```

輸出：

```text
不是管理員或沒有使用者
索引超出範圍
沒有資料
```

如果把三個條件的左右對調，`u.Name` 會因為 `nil` 指標 panic、`nums[5]` 會索引越界 panic、`total/0` 會除以零 panic。

## 與數字不能互轉

在 C、Python、JavaScript 裡，`0` 被當成假、非 0 被當成真。Go 刻意不這麼做：`bool` 與數字是完全不同的型別，不能互相轉換，條件式也只接受 `bool`。這避免了「把 `=` 誤寫成 `==`」或「把計數當成判斷」這類隱藏 bug。

### 不能把數字當條件

注意：在 `if` 裡直接放數字、或寫 `int(true)`，都會編譯失敗：

```go
package main

import "fmt"

func main() {
	count := 3
	if count {
		fmt.Println("有資料")
	}
	fmt.Println(int(true))
}
```

輸出：

```text
$ go build .
# example
./main.go:7:5: non-boolean condition in if statement
./main.go:10:18: cannot convert true (untyped bool constant) to type int
```

要判斷數字，就明確寫出比較：`if count != 0`、`if count > 0`。

### 需要轉換時自己寫

真的需要把布林變成 0／1（例如計算有幾個條件成立），就寫一個小函式；字串與布林的轉換則用 `strconv.ParseBool` 與 `strconv.FormatBool`。`ParseBool` 接受 `1`、`t`、`T`、`TRUE`、`true`、`True` 以及對應的假值，其他字串會回傳錯誤：

```go
package main

import (
	"fmt"
	"strconv"
)

func btoi(b bool) int {
	if b {
		return 1
	}
	return 0
}

func main() {
	passed := []bool{true, false, true, true}
	count := 0
	for _, p := range passed {
		count += btoi(p)
	}
	fmt.Println("通過數:", count)

	for _, s := range []string{"true", "0", "T", "yes"} {
		v, err := strconv.ParseBool(s)
		fmt.Println(s, "→", v, err)
	}
	fmt.Println(strconv.FormatBool(false) + "!")
}
```

輸出：

```text
通過數: 3
true → true <nil>
0 → false <nil>
T → true <nil>
yes → false strconv.ParseBool: parsing "yes": invalid syntax
false!
```

`"yes"` 不在接受清單中，所以回傳錯誤，值是 `false`。讀取環境變數或設定檔的開關時，記得處理這個錯誤。

## 重點整理

- `bool` 只有 `true`、`false`，零值是 `false`；比較運算的結果都是 `bool`
- 邏輯運算子 `!` > `&&` > `||`，混用時加括號
- `&&`、`||` 短路求值：結果確定就不計算右邊，右邊的函式可能不會執行
- 用短路「先檢查再存取」：`p != nil && p.X`、`i < len(s) && s[i]`
- 布林與數字不能互轉，條件式只接受 `bool`；需要時自己寫轉換函式，字串用 `strconv.ParseBool`

## 資料來源

- [gopl-zh/gopl-zh.github.com（《Go 語言聖經》中譯本，章節架構參考）](https://github.com/gopl-zh/gopl-zh.github.com)
- [The Go Programming Language Specification](https://go.dev/ref/spec)
- [Go 官方文件](https://go.dev/doc/)
- [Go 官方部落格](https://go.dev/blog/)
