douxuelv7755 2013-09-22 17:42
浏览 163
已采纳

Go:可变参数函数和太多参数?

Here's an example of the problem I'm having:

package main

import "fmt"

func foo(a int, b ...int) {
    fmt.Println(a,b)
}

func main() {
    a := 0
    aa := 1
    b := []int{2,3,4}
    foo(a, aa, b...)
}

When I run this I get the error too many arguments in call to foo. I guess I could understand why this is happening, but what's not clear to me is how I can get around it without having to make a copy of b with an extra slot at the beginning for aa (which I'd rather not do, as this code would be running quite often and with b being somewhat long).

So my question is: Am I just doing this wrong? And if not, what would be the most efficient way to do what I'm trying to do?

(Also, I can't change the signature of foo).

  • 写回答

2条回答 默认 最新

  • dora12345678 2013-09-22 22:05
    关注

    In the Go runtime a variadic function is implemented as if it had an extra slice parameter at the end instead of a variadic parameter.

    For example:

    func Foo( a int, b ...int )
    func FooImpl( a int, b []int )
    
    c := 10
    d := 20
    
    //This call
    Foo(5, c, d)
    
    // is implemented like this
    b := []int{c, d}
    FooImpl(5, b)
    

    In theory Go could handle the case where some of a variadic arguments are specified directly and the rest are expanded out of an array/slice. But, it would not be efficient.

    //This call
    Foo(5, c, b...)
    
    // would be implemented like this.
    v := append([]int{c},b...)
    FooImpl(5, v)
    

    You can see that Go would be creating a copy of b anyways. The ethos of Go is to be as small as possible and yet still useful. So small features like this get dropped. You may be able to argue for this syntactic sugar, as it can be implemented slightly more efficiently than straight forward approach of append.

    Note that expanding a slice with ... does not create a copy of the underlying array for use as the parameter. The parameter just aliases the variable. In other words it's really efficient.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。