函数返回值类型转换分为两种方式:type assertion 检查值与特定类型是否兼容,不兼容则报错;type conversion 不检查兼容性,直接转换。实战中,可将浮点型转换为整数,或将元组中的整数转换为字符串。
Go 语言中函数返回值的类型转换
在 Go 语言中,函数返回值的类型可以用 type assertion 或 type conversion 来转换。
Type Assertion
使用 type assertion 检查值是否与特定类型兼容,并将该值转换为所期望的类型,如果类型不兼容,会导致错误:
func GetValue() interface{} {
return "Hello, world!"
}
func main() {
value := GetValue()
// 检查 value 是否为字符串类型
if str, ok := value.(string); ok {
fmt.Println(str) // 输出: Hello, world!
}
}




