以下代码是否编译通过:
package main import "fmt" type MyInt1 int type MyInt2 = int func main() { var i int =0 var i1 MyInt1 = i var i2 MyInt2 = i fmt.Println(i1,i2) }
输出结果:
编译不通过,cannot use i (type int) as type MyInt1 in assignment。
MyInt1 和 MyInt2 是int 别名类型,数据类型还是int,但底层做了二次封装;
Go是强数据类型,必须作类型转换才能接收值, 正确做法是:
package main import "fmt" type MyInt1 int type MyInt2 = int func main() { var i int =0 var i1 MyInt1 = MyInt1(i) var i2 MyInt2 = MyInt2(i) fmt.Println(i1,i2) }