【问题标题】:Type assertion failed when using two different (but identical) types使用两种不同(但相同)的类型时,类型断言失败
【发布时间】:2015-08-11 12:39:26
【问题描述】:

我有这个代码

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

【问题讨论】:

标签: go type-assertion


【解决方案1】:

它们不是相同的类型。正如运行时告诉你的那样,一个是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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 2018-03-11
    相关资源
    最近更新 更多