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

Go 语言中函数返回值的类型转换
在 Go 语言中,函数返回值的类型可以用 type assertion 或 type conversion 来转换。
Type Assertion
立即学习“go语言免费学习笔记(深入)”;
使用 type assertion 检查值是否与特定类型兼容,并将该值转换为所期望的类型,如果类型不兼容,会导致错误:
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
以上就是golang函数返回值的类型转换的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号