美文网首页
go评语陷阱之十:字符串不能为"nil"

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

作者: wu_sphinx | 来源:发表于2015-07-25 17:16 被阅读6492次

    字符串不能被赋为"空"

    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)

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/cqlmqttx.html