Home > Backend Development > Golang > Is there a better alternative for golang variadic parameters?

Is there a better alternative for golang variadic parameters?

PHPz
Release: 2024-04-29 12:57:02
Original
1153 people have browsed it

Better alternatives to variadic functions are: Using slices as arguments Using structures as arguments Using function currying

Is there a better alternative for golang variadic parameters?

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:

  • Type unsafe: Parameters of variadic functions do not have explicit types, which may This will cause the type checker to fail to detect the error.
  • Inefficiency: Slices are usually used inside variadic functions, which will bring additional memory allocation and copying overhead.

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
}
Copy after login

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,
    }
}
Copy after login

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]
    }
}
Copy after login

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)
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template