gpt4 book ai didi

golang (*interface{})(nil) 是否为 nil?

转载 作者:IT王子 更新时间:2023-10-29 01:17:09 24 4
gpt4 key购买 nike

代码片段如下:

package main

import (
"fmt"
"reflect"
)

func main() {
a := (*interface{})(nil)
fmt.Println(reflect.TypeOf(a), reflect.ValueOf(a))
var b interface{} = (*interface{})(nil)
fmt.Println(reflect.TypeOf(b), reflect.ValueOf(b))
fmt.Println(a == nil, b == nil)
}

输出如下:

*interface {} <nil>
*interface {} <nil>
true false

所以 var interface{}:= 不同,为什么?

最佳答案

根据 golang faq

Under the covers, interfaces are implemented as two elements, a type and a value. The value, called the interface's dynamic value, is an arbitrary concrete value and the type is that of the value. For the int value 3, an interface value contains, schematically, (int, 3).

An interface value is nil only if the inner value and type are both unset, (nil, nil). In particular, a nil interface will always hold a nil type. If we store a nil pointer of type *int inside an interface value, the inner type will be *int regardless of the value of the pointer: (*int, nil). Such an interface value will therefore be non-nil even when the pointer inside is nil.

a := (*interface{})(nil) 等于 var a *interface{} = nil

但是 var b interface{} = (*interface{})(nil) ,意味着 binterface{} 类型,并且interface{} 变量只有 nil 当它的类型和值都是 nil 时,显然类型 *interface{} 是不是 nil

关于golang (*interface{})(nil) 是否为 nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43059653/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com