Type declaration importance in golang, nil values

huangapple go评论79阅读模式
英文:

Type declaration importance in golang, nil values

问题

我有一个小的 Golang 测试,我无法理解:

package main

import "fmt"

type myObj struct {
}

func nilObj() *myObj {
	return nil
}

func nilInt() interface{} {
	return nil
}

func main() {
	var obj1 interface{}
	fmt.Println(obj1 == nil)	// true
	obj1 = nilObj()
	fmt.Println(obj1 == nil)	// false

	var obj2 *myObj
	fmt.Println(obj2 == nil)	// true
	obj2 = nilObj()
	fmt.Println(obj2 == nil)	// true

	var obj3 interface{}
	fmt.Println(obj3 == nil)	// true
	obj3 = nilInt()
	fmt.Println(obj3 == nil)	// true
}

obj1obj2 之间,只有变量声明不同,但结果不同。

obj1obj3 之间,函数调用返回的类型不同(结构体指针 vs 接口)。我不完全确定我理解结果的方式。

任何帮助都是受欢迎的(https://play.golang.org/p/JcjsJ-_S8I

英文:

I have this small golang test I cannot understand:

package main

import "fmt"

type myObj struct {
}

func nilObj() *myObj {
	return nil
}

func nilInt() interface{} {
	return nil
}

func main() {
	var obj1 interface{}
	fmt.Println(obj1 == nil)	// true
	obj1 = nilObj()
	fmt.Println(obj1 == nil)	// false

	var obj2 *myObj
	fmt.Println(obj2 == nil)	// true
	obj2 = nilObj()
	fmt.Println(obj2 == nil)	// true

	var obj3 interface{}
	fmt.Println(obj3 == nil)	// true
	obj3 = nilInt()
	fmt.Println(obj3 == nil)	// true
}

Between obj1 and obj2, only the variable declaration changes, but the result is different.

Between obj1 and obj3, the function call does not return the same type (struct pointer vs interface). I am not entirely sure I understand the result.

Any help is welcome (https://play.golang.org/p/JcjsJ-_S8I)

答案1

得分: 1

在底层,接口由两个元素实现,一个是类型(type),一个是值(value)。值被称为接口的动态值(dynamic value),它是一个任意的具体值,而类型则是该值的类型。对于整数值3,接口值的示意形式为(int, 3)

只有当内部值和类型都未设置时,接口值才为nil,即(nil, nil)。特别地,nil接口将始终持有一个nil类型。如果我们将类型为*intnil指针存储在接口值中,无论指针的值如何,内部类型都将是*int,即(*int, nil)。因此,即使内部指针为nil,这样的接口值仍然是非nil的。

英文:

> 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.

https://golang.org/doc/faq#nil_error

huangapple
  • 本文由 发表于 2016年12月2日 15:56:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/40927309.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定