go评语陷阱之十:字符串不能为"nil"

2015-07-25  本文已影响6492人  wu_sphinx

字符串不能被赋为"空"

package main

func main() {
    var x string = nil //error

    if x == nil { //error
        x = "default"
    }
}
./hello.go:4: cannot use nil as type string in assignment
./hello.go:6: invalid operation: x == nil (mismatched types string and nil)

看来nil并不代表空的字符串
package main

func main() {  
    var x string //defaults to "" (zero value)

    if x == "" {
        x = "default"
    }
}

发现nil并不能进行比较操作

invalid operation: nil == nil (operator == not defined on nil)
上一篇下一篇

猜你喜欢

热点阅读