命名返回值
本课属于 Coddy GO 学习旅程的“基础知识”单元。第 57 课,共 109 课。
在 Go 中,你可以在函数声明中为返回值命名。这样能让代码更易读,还可以只使用普通的 return 语句来返回。
创建一个使用命名返回值的函数:
func divide(a, b int) (quotient int, remainder int) {
quotient = a / b
remainder = a % b
return // "naked" return 语句
}
func main() {
q, r := divide(7, 3)
fmt.Println("7 ÷ 3 =", q, "with remainder", r)
}输出和之前相同:
7 ÷ 3 = 2 with remainder 1命名返回值会初始化为各自的零值,并且可以在函数体中直接赋值。
挑战
入门在这个挑战中,你将练习在 Go 函数中使用命名返回值。
完成函数 getPersonInfo,让它返回一个人的姓名、年龄,以及这个人是否是学生。函数已经有命名返回参数,但你需要为它们赋值。
函数应返回预定义的值:这个人名叫 'Alex',25 岁,是一名学生。
亲手试试
package main
import "fmt"
// 这个函数使用具名返回值
func getPersonInfo() (name string, age int, isStudent bool) {
// TODO: 给具名返回变量赋值
// name 应设为 "Alex"
// age 应设为 25
// isStudent 应设为 true
// 不带参数的 "return" 语句会返回具名返回值
return
}
func main() {
name, age, isStudent := getPersonInfo()
fmt.Printf("Name: %s\nAge: %d\nStudent: %t\n", name, age, isStudent)
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: Go 在线编译器