使用两种不同(但相同)的类型时类型断言失败

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 相同。有没有不使用相同类型的方法来做到这一点?

它们不是同一类型。正如运行时告诉您的那样,一个是 int,一个是 MyType。 Go 对 identical 有一个非常具体的定义。

直接来自规范:

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

您可以轻松地在两者之间进行转换,MyType(12) 工作得很好,但类型断言与转换不同:https://golang.org/ref/spec#Type_assertions

如果您想阅读一些关于接口和类型以及所有有趣的东西,这些都非常有帮助:

http://blog.golang.org/laws-of-reflection

http://research.swtch.com/interfaces