判斷一個值是否為nil,最好是直接跟nil進行比較判斷,而不要通過interface{}的形參傳給另一個函數來進行判斷。
但是用反射可以通過interface{}來判斷nil,如testnil5。
看如下示例代碼,a是一空指針,但隻有testnil4和testnil5能正确判斷出來:
type State struct {}
func testnil1(a, b interface {}) bool {
return a == b
}
func testnil2(a *State, b interface{}) bool{
return a == b
}
func testnil3(a interface {}) bool {
return a == nil
}
func testnil4(a *State) bool {
return a == nil
}
func testnil5(a interface {}) bool {
v := reflect.ValueOf(a)
return !v.IsValid() || v.IsNil()
}
func main(){
var a *State
fmt.Println(a)
fmt.Println(testnil1(a, nil))
fmt.Println(testnil2(a, nil))
fmt.Println(testnil3(a))
fmt.Println(testnil4(a))
fmt.Println(testnil5(a))
}
輸出結果為:
<nil>
false
false
false
true
true