go 判定对象为nil 在go中,对类型明确的对象,要判定它是不是nil简单 ``` func test1(v *teststr) { if v == nil { fmt.Println("value is nil") return } fmt.Println("value is not nil") } ``` 但是如果参数是一个interface,那情况就不同了。Interface包含类型还有值两个属性。比如: ``` type teststr struct { } func test(i interface{}) bool { v, ok:= i.(*teststr) fmt.Println("type is ok:", ok) if i == nil { fmt.Println("interface is nil") return false } if v == nil { fmt.Println("value is nil") return false } fmt.Println("value and interface is not nil") return true } ``` 当声明一个变量然后传入(值为nil) ``` var nilVal *teststr test(nilVal) // value is nil ``` 传入真正的nil ``` test(nil) // type is ok false \n interface is nil ``` 另外,如果interface传入真正的nil,对它做任何类型断言,都是失败的。 结论: 对于函数,传入值是interface,想判定它是不是nil: ``` func test(i interface{}) bool { // 判定是不是真正的nil if i == nil { fmt.Println("interface is nil") return false } // 做类型断言 v, ok := i.(*teststr) if !ok{ fmt.Println("type is not ok") return false } // 判定断言后的类型的值,是不是nil if v == nil { fmt.Println("value is nil") return false } fmt.Println("value and interface is not nil") return true } ``` 来自 大脸猪 写于 2020-07-03 14:18 -- 更新于2020-10-19 13:06 -- 0 条评论