抛砖引玉的两个例子
intfloat64
invalid operation: a + b (mismatched types int and float64)
intfloat64
intfloat64
cannot use a (type int) as type float64 in assignment
intfloat64
Go语言不支持自动类型转换(Automatic Type Conversion)或隐式类型转换(Implicit Type Conversion)
所以要想上面两个例子成功执行,在此之前我们必须将两个不同类型的变量转为同类型的变量,这时就需要显式类型转换
显式类型转换
显式类型转换(Explicit Type Conversion),其实从英文来看就很好理解,意思是明确的类型转换
T(v)
利用显式类型转换修正上面两个例子:
[1]:
float64int
[2]:
类型别名
就像小时候长辈会给我们取小名,长大学了英语喜欢给自己取个英文名一样,这些就是别名,实际上指代的还是我们这个人
type 类型新名 = 原类型名
注意上面声明变量a时,类型是myint
a + b
builtin
type byte = uint8type rune = int32
byteuint8runeint32
go doc builtin
定义新类型
type 新类型名 原类型名
type myint = inttype myint intmyintintint
执行一下试试看看~
编译失败报错了,因为a与b并不是同一个类型的变量,而且Go不支持自动类型转换
怎么办?有两种办法:
intmyint
总结
see you~