函数返回值类型转换分为两种方式:type assertion 检查值与特定类型是否兼容,不兼容则报错;type conversion 不检查兼容性,直接转换。实战中,可将浮点型转换为整数,或将元组中的整数转换为字符串。

Go 语言中函数返回值的类型转换
在 Go 语言中,函数返回值的类型可以用 type assertion 或 type conversion 来转换。
Type Assertion
立即学习“go语言免费学习笔记(深入)”;
使用 type assertion 检查值是否与特定类型兼容,并将该值转换为所期望的类型,如果类型不兼容,会导致错误:
使用 uber-go/dig 在 Golang 中实现依赖注入——基于反射容器,提供 Provide/Invoke、dig.In/dig.Out 参数与结果对象,支持命名依赖等
func GetValue() interface{} {
return "Hello, world!"
}
func main() {
value := GetValue()
// 检查 value 是否为字符串类型
if str, ok := value.(string); ok {
fmt.Println(str) // 输出: Hello, world!
}
}Type Conversion
使用 type conversion 将值的类型转换为所期望的类型,无论值是否兼容,都会进行转换:
func main() {
var num float64 = 3.14
// 将 float64 转换为 int
numInt := int(num)
fmt.Println(numInt) // 输出: 3
}实战案例
以下是一个实战案例,演示如何转换函数返回值的类型:
func GetEmployeeInfo() (string, int) {
return "John Doe", 30
}
func main() {
name, age := GetEmployeeInfo()
// 将 age 转换为 string 类型
ageStr := strconv.Itoa(age)
fmt.Println("Employee Name:", name)
fmt.Println("Employee Age:", ageStr)
}输出:
Employee Name: John Doe Employee Age: 30

















