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

huangapple go评论80阅读模式
英文:

Convert from type alias to original type

问题

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

type myint int;

现在我有一个名为 foomyint 类型。有没有办法将 foomyint 转换为 int

英文:

Suppose I have a type alias like this:

type myint int;

Now I have a myint type called foo. Is there any way to convert foo from a myint to an int?

答案1

得分: 27

使用转换myint转换为int

package main

import "fmt"

type myint int

func main() {
    foo := myint(1) // foo的类型是myint
    i := int(foo)   // 使用类型转换将myint转换为int
    fmt.Println(i)
}

类型myint不是int的别名,它是一个不同的类型。例如,表达式myint(0) + int(1)无法编译,因为操作数是不同的类型。在Go语言中有两个内置的类型别名,即runebyte。应用程序不能定义自己的别名。

英文:

Use a conversion to convert a myint to an 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)
}

The type myint is a not an alias for int. It's a different type. For example, the expression myint(0) + int(1) does not compile because the operands are different types. There are two built-in type aliases in Go, rune and byte. Applications cannot define their own aliases.

huangapple
  • 本文由 发表于 2014年9月15日 12:54:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/25841042.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定