Go:类型断言 – 规范中是否有错误?

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

Go: Type Assertions - Is there an error in the spec?

问题

Go Spec Type Assertions中是否存在错误?

在赋值语句或特殊形式的初始化中使用的类型断言

v, ok = x.(T)
v, ok := x.(T)
var v, ok = x.(T)
var v, ok interface{} = x.(T) // v和ok的动态类型分别为T和bool

会产生一个额外的无类型布尔值。

最后一个例子var v, ok interface{} = x.(T)是什么意思?

我在Go 1.19中遇到了一个错误
syntax error: unexpected interface, expecting := or = or comma

英文:

Is there an error in the Go Spec Type Assertions?

> A type assertion used in an assignment statement or initialization of the special form
>
> v, ok = x.(T)
> v, ok := x.(T)
> var v, ok = x.(T)
> var v, ok interface{} = x.(T) // dynamic types of v and ok are T and bool
>

> yields an additional untyped boolean value.

What is the last example supposed to be and mean?
var v, ok interface{} = x.(T) ?

I get an error in Go 1.19
syntax error: unexpected interface, expecting := or = or comma

答案1

得分: 1

所有这些行都尝试进行相同的操作:将x断言为类型T。值ok确定断言是否成功。在你提供的最后一个示例中,唯一的区别是,你没有让Go确定vok的类型,而是为它们都提供了interface{}类型。将vok声明为interface{}不会改变它们所包含的值。这将允许你将它们发送到期望interface{}类型的函数或将它们添加到集合中,在这种情况下,它们必须再次进行断言。

英文:

All of those lines are attempting the same operation: a type assertion of x to type T. The value, ok, determines whether or not the assertion was successful. In the last example you provided, the only difference is that instead of Go determining the type for v and ok, you've provided a type of interface{} for both. Declaring v and ok as interface{} doesn't change the values they contain. It would allow you to send them to functions or add them to collections that expect a type of interface{}, at which point they'd have to be asserted again.

huangapple
  • 本文由 发表于 2022年11月21日 07:45:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/74512910.html
匿名

发表评论

匿名网友

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

确定