可变参数函数模板_可变参数函数

可变参数函数模板

Variadic Functions are functions that accept an unlimited number of arguments. Typically, they are expressed in the form

可变参数函数是接受无限数量的参数的函数。 通常,它们以以下形式表示

func hello(friends ...string) {
    // ...
}

Very easy to recognize from the 3 dots ....

很容易从3点认识...

We can call hello() like this:

我们可以这样调用hello()

hello("tony", "mark", "mary", "joe")

or:

要么:

hello("tony")

or with an infinite number of strings.

或无数个字符串。

标准库中的示例: append() (An example from the standard library: append())

append is a variadic function, defined as

append是一个可变参数函数,定义为

func append(slice []Type, elems ...Type) []Type

A common usage is when removing an item at position i from an array a.

一种常见用法是从数组a删除位置i处的项目时。

a = append(a[:i], a[i+1:]...)

This line creates a new slice by removing the item at position i in a, by combining the items from 0 to i (not included), and from i+1 to the end.

这条线通过在位置移除所述项目创建一个新的切片ia ,由从0的项目组合,以I(不包括在内),和从i + 1到最后。

What is the purpose of ...?

...的目的是什么?

append accepts a slice as first argument, and an unlimited number of arguments, all with a type assignable to the type of its elements.

append接受一个slice作为第一个参数,并接受无限数量的参数,所有参数的类型都可分配给其元素的类型。

Writing

写作

a = append(a[:i], a[i+1:]...)

is equivalent as writing

相当于写作

a = append(a[:i], a[i+1], a[i+2], a[i+3], a[i+4]) //and so on, until the end of the slice.

Using a[i+1:]... is basically a shorthand syntax, as the Go spec describes in https://golang.org/ref/spec#Passing_arguments_to_..._parameters:

使用a[i+1:]...基本上是一种速记语法,如Go规范在https://golang.org/ref/spec#Passing_arguments_to_..._parameters中所述

If f is variadic with a final parameter p of type …T, then within f the type of p is equivalent to type []T. If f is invoked with no actual arguments for p, the value passed to p is nil. Otherwise, the value passed is a new slice of type []T with a new underlying array whose successive elements are the actual arguments, which all must be assignable to T

如果f是最终参数p为…T类型的可变参数,则在f内p的类型等效于[] T类型。 如果在没有p实际参数的情况下调用f,则传递给p的值为nil。 否则,传递的值是[] T类型的新切片,带有新的基础数组,其后续元素是实际参数,所有这些参数都必须可分配给T

Playground

操场

翻译自: https://flaviocopes.com/go-variadic-functions/

可变参数函数模板

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值