Booleans
Go doesn't have a quick way to evaluate if something is"truthy".In Python, for example, you can use an if
statement on any type andmost types have a way of automatically converting to True
orFalse
. For example you can do:
- x = 1
- if x:
- print "Yes"
- y = []
- if y:
- print "this won't be printed"
This is not possible in Go. You really need to do it explicitly forevery type:
- x := 1
- if x != 0 {
- fmt.Println("Yes")
- }
- var y []string
- if len(y) != 0 {
- fmt.Println("this won't be printed")
- }
Python
- print True and False # False
- print True or False # True
- print not True # False
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")
- }
- var y []string
- if len(y) != 0 {
- fmt.Println("this won't be printed")
- }
- }