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

字符串不能被赋为"空"

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")