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 package main
import ( import (
"errors"
"fmt" "fmt"
"time"
) )
func exercise1(x, y int) (int, int) { func exercise1(x, y int) (int, int) {
// 返回x+y和x-y // 返回x+y和x-y
return ____, ____ return x + y, x - y
} }
func exercise2(n int) (int, error) { func exercise2(n int) (int, error) {
// 如果n<0,返回0和错误 // 如果n<0,返回0和错误
// 否则返回n和nil // 否则返回n和nil
if ____ { if n < 0 {
return ____, ____ return n, fmt.Errorf("division by zero")
} }
return ____, ____ return n, nil
} }
func exercise3(s string) (bool, int) { func exercise3(s string) (bool, int) {
// 返回字符串是否包含"hello"和字符串长度 // 返回字符串是否包含"hello"和字符串长度
contains := true contains := true
length := ____ length := len(s)
return ____, ____ return contains, length
} }
func main() { func main() {
fmt.Println("=== 多返回值 练习 ===\n") fmt.Println("=== 多返回值 练习 ===")
sum, diff := exercise1(10, 3) sum, diff := exercise1(10, 3)
fmt.Printf("练习1: 加=%d, 减=%d\n", ____, ____) fmt.Printf("练习1: 加=%d, 减=%d\n", sum, diff)
result, err := exercise2(-5) result, err := exercise2(-5)
if ____ { if err != nil {
fmt.Printf("练习2: 错误 = %v\n", ____) fmt.Printf("练习2: 错误 = %v\n", result)
} else { } else {
fmt.Printf("练习2: 结果 = %d\n", ____) fmt.Printf("练习2: 结果 = %d\n", result)
} }
} }