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

Vla*_*ala 5 go

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

type myint int;
Run Code Online (Sandbox Code Playgroud)

现在我有一个myint叫做的类型foo.有没有办法将foo从a myint转换为int

Sim*_*Fox 12

使用转换到转换myintint:

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)
}
Run Code Online (Sandbox Code Playgroud)

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

  • +1 Go 中的类型语义!Scala 的弱点之一是 `type` 使别名不是类型,这可能与直觉相反。去吧,恕我直言。 (2认同)