英文:
Convert from type alias to original type
问题
假设我有一个类型别名,像这样:
type myint int;
现在我有一个名为 foo 的 myint 类型。有没有办法将 foo 从 myint 转换为 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语言中有两个内置的类型别名,即rune和byte。应用程序不能定义自己的别名。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论