| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- package main
- import "fmt"
- // 1. 无参数、无返回值。main 可以调用它,函数定义不必放在 main 前面。
- func greet() {
- fmt.Println("欢迎学习 Go 函数")
- }
- // 2. 参数类型写在名称后面,返回值类型写在参数列表后面。
- // 相同类型的相邻参数,可以简写成 a, b int。
- func add(a, b int) int {
- return a + b
- }
- // 3. int 参数按值传递:修改形参不会修改调用方的整数变量。
- func increase(value int) int {
- value++
- return value
- }
- // 4. 多返回值:用 bool 表示本次计算是否有效。
- // 本课先用 bool,后续再学习 Go 中常见的 (结果, error) 形式。
- func average(scores []int) (float64, bool) {
- if len(scores) == 0 {
- return 0, false // 提前返回,避免空切片导致除以零。
- }
- total := 0
- for _, score := range scores {
- total += score
- }
- return float64(total) / float64(len(scores)), true
- }
- // 5. 可变参数:可接收零个或多个 int,函数内部 values 是 []int。
- func sum(values ...int) int {
- total := 0
- for _, value := range values {
- total += value
- }
- return total
- }
- func main() {
- fmt.Println("=== 无参数函数 ===")
- greet()
- fmt.Println("\n=== 参数与返回值 ===")
- result := add(2, 3)
- fmt.Printf("2 + 3 = %d\n", result)
- fmt.Println("\n=== 值传递 ===")
- count := 10
- next := increase(count)
- fmt.Printf("原变量:%d,函数返回的新值:%d\n", count, next)
- fmt.Println("\n=== 多返回值与提前返回 ===")
- scores := []int{80, 90, 85}
- avg, ok := average(scores)
- if ok {
- fmt.Printf("平均分:%.2f\n", avg)
- }
- _, ok = average(nil) // 不需要结果时,用 _ 忽略它。
- if !ok {
- fmt.Println("没有成绩,无法计算平均分")
- }
- fmt.Println("\n=== 可变参数 ===")
- fmt.Printf("直接传入多个整数:%d\n", sum(1, 2, 3))
- numbers := []int{10, 20, 30}
- fmt.Printf("展开切片作为参数:%d\n", sum(numbers...))
- fmt.Printf("不传参数:%d\n", sum())
- }
|