混合“爆炸”切片和可变参数中的常规参数 [英] mixing "exploded" slices and regular parameters in variadic functions

查看:85
本文介绍了混合“爆炸”切片和可变参数中的常规参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  func main(){$ b $ 

我想知道为什么无法在go中执行以下操作: b stuff:= [] string {baz,bla}
foo(bar,stuff ...)
}

func foo(s .. .string){
fmt.Println(s)
}

在我的理解,切片......爆炸切​​片,以便它可用于多参数函数调用。所以上面的例子应该扩展到 foo(bar,baz,bla)

foo(stuff ...)按预期工作,这里没有意外,但在上面的例子中,编译器会抱怨太多争论。



这是一个理想的限制吗?我来自一个红宝石背景,其中 foo(bar,* stuff)是完全正确的(至少在我的书中是这样),这就是为什么这让我感到惊讶。

解决方案

可以通过枚举指定variadic参数的值。使用现有切片的元素,由名称指定,后跟 ...



您想混合Go语言规范所不允许的两种可能方式(将参数传递给<
$ b

如果使用了第一种形式(枚举元素): ... / p>


传递的值[作为可变参数]是类型为 [] T

切片后跟 ... 没有创建新切片,您传递的切片将按原样使用。传递的片段只能用于指定 1 - final - 可变参数的值。尝试传递单个元素时,切片与您的函数的签名(本例中为参数列表)不匹配,您将收到错误消息:

 调用foo中的参数太多

Go中没有涉及到实际的爆炸,该术语仅用于其他语言,以帮助可视化传递的数组或切片不会是可变参数的元素,而是值可变参数本身



混合2需要分配一个新的分片,因为显然现有的分片不能被使用。


I'm wondering why it's not possible to do the following in go:

func main() {
    stuff := []string{"baz", "bla"}
    foo("bar", stuff...)
}

func foo(s ...string) {
    fmt.Println(s)
}

In my understanding, slice... "explodes" the slice so it can be used for multi argument function calls. So the above example should actually expand to foo("bar", "baz", "bla").

foo(stuff...) works as expected, no surprises here, but in the example above, the compiler complains about too many arguments.

Is this a desired limitation? I'm coming from a ruby background where a foo("bar", *stuff) is perfectly fine (and is, at least in my book, the same thing), that's why this surprises me.

解决方案

The value for a variadic argument can be specified either by enumerating the elements, or using an existing slice, specified by its name followed by ....

You want to mix the 2 possible ways which is not permitted by the Go Language Specification (Passing arguments to ... parameters).

If the first form is used (enumerating the elements):

The value passed [as the variadic parameter] is a new slice of type []T with a new underlying array whose successive elements are the actual arguments.

If the latter is used (passing an existing slice followed by ...) no new slice is created, the one you pass is used as is. And the passed slice can only be used to specify the value of one – the final – variadic parameter. Attempting to pass both a single element and a slice will not match the signature (the parameter list in this case) of your function and you'll get an error:

too many arguments in call to foo

There is no actual "exploding" involved in Go, the term is just used in other languages to help visualize that the passed array or slice will not be an element of the variadic parameter but will be the value of variadic parameter itself.

Mixing the 2 would require to allocate a new slice because obviously the existing slice cannot be used.

这篇关于混合“爆炸”切片和可变参数中的常规参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆