从类型别名转换为原始类型

时间:2014-09-15 04:54:38

标签: go

假设我有这样的类型别名:

type myint int;

现在我有一个名为myint的{​​{1}}类型。有没有办法将foo从foo转换为myint

1 个答案:

答案 0 :(得分:11)

使用conversionmyint转换为int

package main

import "fmt"

type myint int

func main() {
    foo := myint(1) // foo has type myint
    i := int(foo)   // use type conversion to convert myint to int
    fmt.Println(i)
}

类型myint不是int的别名。这是一种不同的类型。例如,表达式myint(0) + int(1)无法编译,因为操作数是不同的类型。 Go,rune和byte中有两个内置类型别名。应用程序无法定义自己的别名。