英文:
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确定v和ok的类型,而是为它们都提供了interface{}类型。将v和ok声明为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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论