学习Golang。逻辑运算符
布尔代数
布尔代数是关于应用于布尔值的逻辑运算true 和false 。
最常见的操作是 "和"(结合)、"或"(分离)和 "不"(否定)。
有趣的是:它被称为 "布尔",因为它是由乔治-布尔在1847年提出的。
逻辑运算符
Go为布尔代数提供了三个运算符,称为 "逻辑运算符":
&&:和运算符。||:OR运算符。!:非运算符。
而且
&& 算子接受两个布尔值,当且仅当其操作数都是true ,它才会产生true 。
换句话说:p && q 是 "如果p then q else false"。
以表格的形式:
| true | 假 | |
|---|---|---|
| 真 | 真 | 错误 |
| 虚假 | 虚假 | 虚假 |
例子:
package main
import (
"os"
"bufio"
"fmt"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Are the lights on (y/n)? ")
lightsOnInput, _ := reader.ReadString('\n')
lightsOnCleaned := strings.TrimSuffix(lightsOnInput, "\n")
lightsOn := lightsOnCleaned == "y"
fmt.Print("Is the door open (y/n)? ")
doorOpenInput, _ := reader.ReadString('\n')
doorOpenCleaned := strings.TrimSuffix(doorOpenInput, "\n")
doorOpen := doorOpenCleaned == "y"
if lightsOn && doorOpen {
fmt.Println("Go in.")
} else {
fmt.Println("Come back later.")
}
}
运行样本:
❯ bin/go run ./logical/and.go
Are the lights on (y/n)? y
Is the door open (y/n)? y
Go in.
❯ bin/go run ./logical/and.go
Are the lights on (y/n)? n
Is the door open (y/n)? y
Come back later.
❯ bin/go run ./logical/and.go
Are the lights on (y/n)? y
Is the door open (y/n)? n
Come back later.
或
|| 操作符接收两个布尔值,如果它的任何一个操作数是true (或者两个都是true ),它就产生true 。
换句话说:p || q 是 "如果p那么真,否则q"。
以表格的形式:
| true | 假 | |
|---|---|---|
| true | true | 真 |
| 错误 | 真 | 错误 |
例子:
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("What day of the week is it? ")
dowInput, _ := reader.ReadString('\n')
dow := strings.TrimSuffix(dowInput, "\n")
if dow == "Saturday" || dow == "Sunday" {
fmt.Println("Stay home.")
} else {
fmt.Println("Go to work.")
}
}
运行样本:
❯ bin/go run ./logical/or.go
What day of the week is it? Saturday
Stay home.
❯ bin/go run ./logical/or.go
What day of the week is it? Sunday
Stay home.
❯ bin/go run ./logical/or.go
What day of the week is it? Monday
Go to work.
不是
! 操作符如果其操作数是false ,则返回true ;如果其操作数是true ,则返回false 。它反转("否定")了其操作数的值。
换句话说:!p 是 "非p"。
以表格的形式:
| ! | |
|---|---|
| 真 | 假的 |
| 假的 | 真 |
例子:
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Are you hungry (y/n)? ")
hungryInput, _ := reader.ReadString('\n')
hungryCleaned := strings.TrimSuffix(hungryInput, "\n")
hungry := hungryCleaned == "y"
notHungry := !hungry
fmt.Println("You are hungry:", hungry)
fmt.Println("You are satisfied:", notHungry)
}
运行样本:
❯ bin/go run ./logical/not.go
Are you hungry (y/n)? y
You are hungry: true
You are satisfied: false
❯ bin/go run ./logical/not.go
Are you hungry (y/n)? n
You are hungry: false
You are satisfied: true
经验之谈
- Go有三个运算符用于布尔运算:
&&(和)、||(或)和!(非)。 - 这些运算符对于为
if语句编写条件非常有用。 - 当需要根据一个或多个布尔值来产生一个布尔值时,它们也很有用。
- 关系运算符(如
==,<,>, 等)返回布尔值,在布尔表达式中容易使用。