Home >Backend Development >Golang >Is there a better alternative for golang variadic parameters?
Better alternatives to variadic functions are: Using slices as arguments Using structures as arguments Using function currying
Go variadic arguments A better alternative to
Variadic functions in Go allow passing any number of arguments via the ...
syntax. While this is convenient in some cases, it also has its limitations, including:
Alternatives
There are several alternatives to variadic functions:
1. Use slices as parameters :
func max(numbers []int) int { if len(numbers) == 0 { return 0 } max := numbers[0] for _, n := range numbers { if n > max { max = n } } return max }
2. Use structs as parameters:
type Stats struct { Mean float64 Median float64 Mode float64 } func calcStats(nums []float64) Stats { // ... 计算统计数据并填充 `Stats` struct return Stats{ Mean: mean, Median: median, Mode: mode, } }
3. Use function currying:
Currying is the process of converting a multi-parameter function into a series of single-parameter functions. For example, we can curry the max
function:
func maxCurried(ns ...int) int { return func(n int) int { if n > ns[0] { ns[0] = n } return ns[0] } }
Practical case
Suppose we have a function that needs to calculate a series of integers Maximum value, let's compare the efficiency of using variadic functions and slicing functions:
package main import ( "fmt" "time" ) func maxVarargs(nums ...int) int { if len(nums) == 0 { return 0 } max := nums[0] for _, n := range nums { if n > max { max = n } } return max } func maxSlice(nums []int) int { if len(nums) == 0 { return 0 } max := nums[0] for _, n := range nums { if n > max { max = n } } return max } func main() { // 产生一个包含 100 万个随机整数的切片 nums := make([]int, 1000000) for i := range nums { nums[i] = rand.Int() } // 使用可变参数函数计算最大值 start := time.Now() maxVarargs(nums...) elapsedVarargs := time.Since(start) // 使用切片函数计算最大值 start = time.Now() maxSlice(nums) elapsedSlice := time.Since(start) fmt.Println("MaxVarargs execution time:", elapsedVarargs) fmt.Println("MaxSlice execution time:", elapsedSlice) }
Run this program, we will see that the slicing function is significantly faster than the variadic function.
The above is the detailed content of Is there a better alternative for golang variadic parameters?. For more information, please follow other related articles on the PHP Chinese website!