Finish: 02-multiple-returns - 多返回值

This commit is contained in:
2026-03-17 15:53:13 +08:00
parent d570ed6810
commit 9b6e6badaa
+11 -13
View File
@@ -1,42 +1,40 @@
package main
import (
"errors"
"fmt"
"time"
)
func exercise1(x, y int) (int, int) {
// 返回x+y和x-y
return ____, ____
return x + y, x - y
}
func exercise2(n int) (int, error) {
// 如果n<0,返回0和错误
// 否则返回n和nil
if ____ {
return ____, ____
if n < 0 {
return n, fmt.Errorf("division by zero")
}
return ____, ____
return n, nil
}
func exercise3(s string) (bool, int) {
// 返回字符串是否包含"hello"和字符串长度
contains := true
length := ____
return ____, ____
length := len(s)
return contains, length
}
func main() {
fmt.Println("=== 多返回值 练习 ===\n")
fmt.Println("=== 多返回值 练习 ===")
sum, diff := exercise1(10, 3)
fmt.Printf("练习1: 加=%d, 减=%d\n", ____, ____)
fmt.Printf("练习1: 加=%d, 减=%d\n", sum, diff)
result, err := exercise2(-5)
if ____ {
fmt.Printf("练习2: 错误 = %v\n", ____)
if err != nil {
fmt.Printf("练习2: 错误 = %v\n", result)
} else {
fmt.Printf("练习2: 结果 = %d\n", ____)
fmt.Printf("练习2: 结果 = %d\n", result)
}
}