从类型别名转换为原始类型 [英] Convert from type alias to original type
本文介绍了从类型别名转换为原始类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个这样的类型别名:
Suppose I have a type alias like this:
type myint int;
现在,我有一个 myint
类型,称为 foo
.有什么方法可以将foo从 myint
转换为 int
?
Now I have a myint
type called foo
. Is there any way to convert foo from a myint
to an int
?
推荐答案
使用转换进行将 myint
转换为 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中有两个内置的类型别名,符文和字节.应用程序无法定义自己的别名.
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.
这篇关于从类型别名转换为原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文