7. 布尔值-Booleans

Go并没有一种快速的方法来评估某些东西是否“真实”。例如,在Python中,您可以在任何类型上使用if语句,并且大多数类型都可以自动转换为True或False。

例如,您可以执行以下操作:

x = 1
if x:
    print("Yes")
y = []
if y:
    print("this won't be printed")

在Go中这是不可能的。您确实需要为每个类型明确地执行此操作

package main

import "fmt"

func main() {
    x := 1
    if x != 0 {
        fmt.Println("Yes")      //Yes
    }

    var y []string
    if len(y) != 0 {
        fmt.Println("this won't be printed")
    }
}

7.1. Python

print(True and False)  # False
print(True or False)  # True
print(not True)  # False

7.2. Go

package main

import "fmt"

func main() {
    fmt.Println(true && false) // false
    fmt.Println(true || false) // true
    fmt.Println(!true)         // false

    x := 1
    if x != 0 {
        fmt.Println("Yes") //Yes
    }

    var y []string
    if len(y) != 0 {
        fmt.Println("this won't be printed")
    }
}