将nil转换为指针类型的Go类型断言。

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

Go type assert nil to pointer type

问题

为什么我不能将nil类型断言为指针类型?这背后的逻辑是什么?

package main

func main() {
    var s interface{} = nil
    var p *string = nil
    var q *string = s.(*string)
    _ = q
    _ = p
}

为什么我不能将nil类型断言为指针类型?这背后的逻辑是什么?

英文:

Why can't I type-assert a nil to a pointer type? What is the logic behind this?

package main

func main() {
	var s interface{} = nil
	var p *string = nil
	var q *string = s.(*string)
	_ = q
	_ = p
}

答案1

得分: 3

你无法对没有类型的内容进行类型断言。

静态类型(或者只是类型)是在变量声明中给出的类型,new调用或复合字面量中提供的类型,或者结构化变量的元素的类型。接口类型的变量也有一个独特的动态类型,在运行时分配给变量的值的具体类型(除非该值是预声明的标识符nil,它没有类型)。动态类型可能会在执行过程中变化,但存储在接口变量中的值始终可以赋值给变量的静态类型。

直接引用自规范(我强调的部分)

接口知道底层值的类型。例如,如果我有一个带有type MyType的接口,它也不能被断言为*string。你可以通过一些工作来转换它的类型,但类型断言和类型转换是不同的。

还可以参考这里

对于一个接口类型的表达式x和类型T,主表达式

x.(T)

断言x不是nil,并且存储在x中的值是类型T。表示为x.(T)。

英文:

You can't type assert something with no type.

> The static type (or just type) of a variable is the type given in its
> declaration, the type provided in the new call or composite literal,
> or the type of an element of a structured variable. Variables of
> interface type also have a distinct dynamic type, which is the
> concrete type of the value assigned to the variable at run time
> (unless the value is the predeclared identifier nil, which has no
> type).
The dynamic type may vary during execution but values stored in
> interface variables are always assignable to the static type of the
> variable.

Straight from the spec (emphasis mine)

Interfaces know the type of the underlying value. For instance if I have a interface with a type MyType it can't be type asserted to *string either. You could perhaps convert its type with some work, but type assertion and type conversion are different.

Also take a look here

> For an expression x of interface type and a type T, the primary
> expression
>
> x.(T)
>
> asserts that x is not nil and that the value stored in x is of
> type T. The notation x.(T)

huangapple
  • 本文由 发表于 2015年8月26日 11:49:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/32217683.html
匿名

发表评论

匿名网友

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

确定