douyao2529 2015-08-10 23:34
浏览 8
已采纳

使用两种不同(但相同)的类型时,类型声明失败

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条回答 默认 最新

  • duanqiangwu9332 2015-08-11 04:29
    关注

    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:

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

    http://research.swtch.com/interfaces

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?