main.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package main
  2. import "fmt"
  3. // 1. 无参数、无返回值。main 可以调用它,函数定义不必放在 main 前面。
  4. func greet() {
  5. fmt.Println("欢迎学习 Go 函数")
  6. }
  7. // 2. 参数类型写在名称后面,返回值类型写在参数列表后面。
  8. // 相同类型的相邻参数,可以简写成 a, b int。
  9. func add(a, b int) int {
  10. return a + b
  11. }
  12. // 3. int 参数按值传递:修改形参不会修改调用方的整数变量。
  13. func increase(value int) int {
  14. value++
  15. return value
  16. }
  17. // 4. 多返回值:用 bool 表示本次计算是否有效。
  18. // 本课先用 bool,后续再学习 Go 中常见的 (结果, error) 形式。
  19. func average(scores []int) (float64, bool) {
  20. if len(scores) == 0 {
  21. return 0, false // 提前返回,避免空切片导致除以零。
  22. }
  23. total := 0
  24. for _, score := range scores {
  25. total += score
  26. }
  27. return float64(total) / float64(len(scores)), true
  28. }
  29. // 5. 可变参数:可接收零个或多个 int,函数内部 values 是 []int。
  30. func sum(values ...int) int {
  31. total := 0
  32. for _, value := range values {
  33. total += value
  34. }
  35. return total
  36. }
  37. func main() {
  38. fmt.Println("=== 无参数函数 ===")
  39. greet()
  40. fmt.Println("\n=== 参数与返回值 ===")
  41. result := add(2, 3)
  42. fmt.Printf("2 + 3 = %d\n", result)
  43. fmt.Println("\n=== 值传递 ===")
  44. count := 10
  45. next := increase(count)
  46. fmt.Printf("原变量:%d,函数返回的新值:%d\n", count, next)
  47. fmt.Println("\n=== 多返回值与提前返回 ===")
  48. scores := []int{80, 90, 85}
  49. avg, ok := average(scores)
  50. if ok {
  51. fmt.Printf("平均分:%.2f\n", avg)
  52. }
  53. _, ok = average(nil) // 不需要结果时,用 _ 忽略它。
  54. if !ok {
  55. fmt.Println("没有成绩,无法计算平均分")
  56. }
  57. fmt.Println("\n=== 可变参数 ===")
  58. fmt.Printf("直接传入多个整数:%d\n", sum(1, 2, 3))
  59. numbers := []int{10, 20, 30}
  60. fmt.Printf("展开切片作为参数:%d\n", sum(numbers...))
  61. fmt.Printf("不传参数:%d\n", sum())
  62. }