gopl-zh.github.com/ch3/ch3-04.md

53 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

## 3.4. 布爾型
一個布爾類型的值隻有兩種true和false。if和for語句的條件部分都是布爾類型的值併且==和<等比較操作也會産生布爾型的值。一元操作符`!`對應邏輯非操作,因此`!true`的值爲`false`,更羅嗦的説法是`(!true==false)==true`雖然表達方式不一樣不過我們一般會采用簡潔的布爾表達式就像用x來表示`x==true`。
布爾值可以和&&AND和||OR操作符結合併且可能會有短路行爲如果運算符左邊值已經可以確定整個布爾表達式的值那麽運算符右邊的值將不在被求值因此下面的表達式總是安全的
```Go
s != "" && s[0] == 'x'
```
其中s[0]操作如果應用於空字符串將會導致panic異常。
因爲`&&`的優先級比`||`高(助記:`&&`對應邏輯乘法,`||`對應邏輯加法,乘法比加法優先級要高),下面形式的布爾表達式是不需要加小括弧的:
```Go
if 'a' <= c && c <= 'z' ||
'A' <= c && c <= 'Z' ||
'0' <= c && c <= '9' {
// ...ASCII letter or digit...
}
```
布爾值併不會隱式轉換爲數字值0或1反之亦然。必鬚使用一個顯式的if語句輔助轉換
```Go
i := 0
if b {
i = 1
}
```
如果需要經常做類似的轉換, 包裝成一個函數會更方便:
```Go
// btoi returns 1 if b is true and 0 if false.
func btoi(b bool) int {
if b {
return 1
}
return 0
}
```
數字到布爾型的逆轉換則非常簡單, 不過爲了保持對稱, 我們也可以包裝一個函數:
```Go
// itob reports whether i is non-zero.
func itob(i int) bool { return i != 0 }
```