Files
go-basics/stage03-functions/01-basic-functions/main.go
T

92 lines
2.0 KiB
Go
Raw Normal View History

2026-03-13 23:54:07 +08:00
package main
2026-03-17 15:46:46 +08:00
import (
"fmt"
"strings"
)
2026-03-13 23:54:07 +08:00
func exercise1() int {
fmt.Println("=== 练习1:无参数单返回值函数 ===")
// 定义一个函数square,接收一个int参数,返回其平方
// 定义一个函数cube,接收一个int参数,返回其立方
// 调用这两个函数并返回它们的和
2026-03-17 15:46:46 +08:00
square := func(n int) int { return n * n }
2026-03-13 23:54:07 +08:00
2026-03-17 15:46:46 +08:00
cube := func(n int) int { return n * n * n }
2026-03-13 23:54:07 +08:00
2026-03-17 15:46:46 +08:00
return square(3) + cube(2)
2026-03-13 23:54:07 +08:00
}
func exercise2(a, b int) {
fmt.Println("\n=== 练习2:多个参数 ===")
// 定义一个函数,接收两个int参数a和b
// 打印a + b, a - b, a * b
// 格式: "加: 5, 减: 1, 乘: 6"
2026-03-17 15:46:46 +08:00
sum := a + b
difference := a - b
product := a * b
fmt.Printf("加: %d, 减: %d, 乘: %d\n", sum, difference, product)
2026-03-13 23:54:07 +08:00
}
func exercise3(nums ...int) int {
fmt.Println("\n=== 练习3:可变参数 ===")
// 定义一个可变参数函数,计算所有数字的和
2026-03-17 15:46:46 +08:00
sum := 0
for _, num := range nums {
sum += num
2026-03-13 23:54:07 +08:00
}
2026-03-17 15:46:46 +08:00
return sum
2026-03-13 23:54:07 +08:00
}
func exercise4(name, city string) (string, string) {
fmt.Println("\n=== 练习4:命名返回值 ===")
// 使用命名返回值,返回两个字符串
// nameWithGreeting: 格式为 "Hello, {name}"
// info: 格式为 "{name} lives in {city}"
2026-03-17 15:46:46 +08:00
var nameWithGreeting string
var info string
2026-03-13 23:54:07 +08:00
nameWithGreeting = fmt.Sprintf("Hello, %s", name)
info = fmt.Sprintf("%s lives in %s", name, city)
2026-03-17 15:46:46 +08:00
return nameWithGreeting, info
2026-03-13 23:54:07 +08:00
}
func exercise5(name string) string {
fmt.Println("\n=== 练习5:匿名函数 ===")
// 使用匿名函数,对name进行处理
// 返回大写的name
// 提示:使用strings.ToUpper
2026-03-17 15:46:46 +08:00
upperName := strings.ToUpper(name)
2026-03-13 23:54:07 +08:00
2026-03-17 15:46:46 +08:00
return upperName
2026-03-13 23:54:07 +08:00
}
func main() {
2026-03-17 15:46:46 +08:00
fmt.Println("=== 基础函数 练习 ===")
2026-03-13 23:54:07 +08:00
result1 := exercise1()
fmt.Printf("练习1结果: %d\n", result1)
exercise2(3, 2)
result3 := exercise3(1, 2, 3, 4, 5)
fmt.Printf("练习3结果: %d\n", result3)
s4, i4 := exercise4("张三", "北京")
fmt.Printf("练习4结果: %s, %s\n", s4, i4)
result5 := exercise5("hello world")
fmt.Printf("练习5结果: %s\n", result5)
}