最近用interface
比较多,因此需要接触断言,有时会与类型转换函数搞混,因此了解一下断言和其用法,具体如下:
断言的应用
var temp interface{}
temp := "abcd"
fmt.Printfln(temp.(string))
可以看出类型断言的使用场景为:当某个类型为interface{}
的变量,真实类型为A时,才做某件事时,这时可以使用类型断言。
而普通的类型转化用法如下:
#string到int
int,err:=strconv.Atoi(string)
#string到int64
int64, err := strconv.ParseInt(string, 10, 64)
#int到string
string:=strconv.Itoa(int)
#int64到string
string:=strconv.FormatInt(int64,10)
其应用场景不同,虽然有时所起到的作用是相同的,这点要特别注意。