var intTest32 int32 = 2147483647
var intTest64 int64 = 2147483648
intTest32 = int32(intTest64)
fmt.Println(intTest32)
fmt.Println(intTest64)
结果:
-2147483648
2147483648
再看看下面普通类型转换报错的代码:
func main() {
i := 0
var a float32
a = 0.9
i = a //cannot use `a` (type float32) as type int assignment
var b float64
b = a//cannot use `a` (type float32) as type float64 assignment
var intTest int32
intTest = 12
var intTest2 int8
intTest2 = intTest ////cannot use `intTest` (type int32) as type int8 assignment
}
uint8 the set of all unsigned 8-bit integers (0 to 255)
uint16 the set of all unsigned 16-bit integers (0 to 65535)
uint32 the set of all unsigned 32-bit integers (0 to 4294967295)
uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)
int8 the set of all signed 8-bit integers (-128 to 127)
int16 the set of all signed 16-bit integers (-32768 to 32767)
int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
var i1 int = 1
var i2 int8 = 2
var i3 int16 = 3
var i4 int32 = 4
var i5 int64 = 5
fmt.Println(unsafe.Sizeof(i1))
fmt.Println(unsafe.Sizeof(i2))
fmt.Println(unsafe.Sizeof(i3))
fmt.Println(unsafe.Sizeof(i4))
结果是:
8
1
2
4
8
看下unsafe.Sizeof的注释:
// Sizeof takes an expression x of any type and returns the size in bytes sizeof可以接受任何类型的表达式,返回的是以比特为单位的大小
// of a hypothetical variable v as if v was declared via var v = x.
// The size does not include any memory possibly referenced by x.
// For instance, if x is a slice, Sizeof returns the size of the slice
// descriptor, not the size of the memory referenced by the slice.
// The return value of Sizeof is a Go constant.
func Sizeof(x ArbitraryType) uintptr
var strTest string = "testing"
t := interface{}(strTest)
if newt, ok := t.(int8); ok {//注意这里变了
fmt.Println(newt)
fmt.Println("转换成功")
fmt.Println(reflect.TypeOf(newt))
} else {
fmt.Println("转换不成功")
fmt.Println(newt)
fmt.Println(reflect.TypeOf(newt))
}