douxuelv7755 2013-09-22 09: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 14: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条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥50 大二的web前段开发静态网页纸质版
  • ¥15 robocopy文件复制
  • ¥15 unity安卓打包出现问题
  • ¥15 爱快路由器端口更改错误导致无法访问
  • ¥20 安装catkin时遇到了如下问题请问该如何解决呢
  • ¥15 VAE模型如何输出结果
  • ¥15 编译python程序为pyd文件报错:{"source code string cannot contain null bytes"
  • ¥20 关于#r语言#的问题:广义加行模型拟合曲线后如何求拐点
  • ¥15 fluent设置了自动保存后,会有几个时间点不保存
  • ¥20 激光照射到四象线探测器,通过液晶屏显示X、Y值
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部