英文:
Type assertion failed when using two different (but identical) types
问题
我有这段代码
package main
import "fmt"
type MyType int
func main() {
var i interface{} = 12
f := i.(MyType)
fmt.Println(f)
}
然而,我得到了这个错误:
panic: interface conversion: interface is int, not main.MyType
然而,在这种情况下,int与MyType是相同的。有没有办法在不使用相同类型的情况下完成这个操作?
英文:
I have this code
package main
import "fmt"
type MyType int
func main() {
var i interface{} = 12
f := i.(MyType)
fmt.Println(f)
}
However, I get this error:
panic: interface conversion: interface is int, not main.MyType
However, int is, in this case, the same as MyType. Is there any way to do this without using the same type?
答案1
得分: 3
它们不是相同的类型。正如运行时所告诉你的那样,一个是int
,另一个是MyType
。Go语言对相同性有非常明确的定义。
直接来自规范:
类型声明将一个标识符(类型名称)绑定到一个具有与现有类型相同底层类型的新类型,并且为现有类型定义的操作也适用于新类型。新类型与现有类型不同。
https://golang.org/ref/spec#Type_identity
https://golang.org/ref/spec#Type_declarations
https://golang.org/ref/spec#Types
你可以很容易地在两者之间进行转换,MyType(12)
可以正常工作,但类型断言与转换是不同的:https://golang.org/ref/spec#Type_assertions
如果你想阅读一些关于接口、类型和其他有趣内容的文章,这两个链接都非常有帮助:
http://blog.golang.org/laws-of-reflection
http://research.swtch.com/interfaces
英文:
They're not identical types. As the runtime tells you, one is int
and one is MyType
. Go has a very specific definition of identical.
Straight from the spec:
> A type declaration binds an identifier, the type name, to a new type
> that has the same underlying type as an existing type, and operations
> defined for the existing type are also defined for the new type. The
> new type is different from the existing type.
https://golang.org/ref/spec#Type_identity
https://golang.org/ref/spec#Type_declarations
https://golang.org/ref/spec#Types
You can easily convert between the two, MyType(12)
works just fine, but type assertion is different from converting: https://golang.org/ref/spec#Type_assertions
If you'd like to do some reading about interfaces and types and all of that fun stuff, these are both super helpful:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论