Go语言常用条件判断空值逻辑的使用

在 Go 中,有几种不同的方法来检查一个值是null还是empty。您应该使用的具体方法取决于您正在检查的值的类型。

例如,如果你正在检查一个字符串是否为空,你可以使用内置len函数来检查字符串的长度

if len(str) == 0 {
    // The string is empty
}

可以使用==运算符将字符串与空字符串进行比较

if str == "" {
    // The string is empty
}

如果要检查整数、浮点数或布尔值是否为零,则可以使用==运算符将值与零进行比较

if i == 0 {
    // The integer is zero
}

if f == 0.0 {
    // The float is zero
}

if b == false {
    // The boolean is false
}

如果要检查切片、映射或通道是否为空,则可以使用该len函数来检查值的长度

if len(slice) == 0 {
    // The slice is empty
}

if len(map) == 0 {
    // The map is empty
}

if len(channel) == 0 {
    // The channel is empty
}

如如果要检查指针是否为nil,则可以使用==运算符将指针与 进行比较nil

if ptr == nil {
    // The pointer is nil
}

如在 Go 中,没有像其他一些语言中那样的"null"值的概念。如果你想在 Go 中表示一个"null"值,你可以使用指针类型并将其设置为nil. 例如nil

var i *int
fmt.Println(i) // prints "nil"

原文地址:https://blog.csdn.net/asd1358355022/article/details/128408247