Variadic Function

Variadic Function - 可变参数函数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package main

import (
	"fmt"
	"math"
)

func findMax(nums ...int) int {
	max := math.MinInt
	for _, num := range nums {
		if num > max {
			max = num
		}
	}
	return max
}

func ConcatStrs(sep string, strs ...string) (r string) {
	for i, str := range strs {
		if i > 0 {
			r += sep
		}
		r += str
	}
	return r
}

func main() {
	fmt.Println(findMax(1, 2, 3)) // 3

	fmt.Println(findMax([]int{1, 2, 3}...)) // 3

	fmt.Println(ConcatStrs("|", "a", "b", "c")) // a|b|c

	fmt.Println(ConcatStrs("|", []string{"a", "b", "c"}...)) // a|b|c
}
最后修改 October 10, 2024: 更新 (a4b8f85)