What does `append()…` do in Go

huangapple go评论84阅读模式
英文:

What does `append()...` do in Go

问题

append()... 是 Go 语言中的一种语法,用于将切片(slice)的元素逐个添加到另一个切片中。在你提供的代码中,append(options, httptransport.ServerBefore(opentracing.FromHTTPRequest(tracer, "calling HTTP POST /endpoint", logger)))... 的作用是将 httptransport.ServerBefore(opentracing.FromHTTPRequest(tracer, "calling HTTP POST /endpoint", logger)) 返回的切片元素逐个添加到 options 切片中。

简而言之,append(options, httptransport.ServerBefore(opentracing.FromHTTPRequest(tracer, "calling HTTP POST /endpoint", logger)))... 的作用是将 httptransport.ServerBefore(opentracing.FromHTTPRequest(tracer, "calling HTTP POST /endpoint", logger)) 返回的切片元素添加到 options 切片中。

英文:

I have this Go code

kithttp.NewServer(
	endpoints.AuthorizeUserEndpoint,
	decodeRequest,
	encodeResponse,
	append(options, httptransport.ServerBefore(opentracing.FromHTTPRequest(tracer, "calling HTTP POST /endpoint", logger)))...,
)

Could you explain me what does append()... do with ... in the end.

答案1

得分: 5

append是一个内置函数,用于将元素追加到切片的末尾。

文档中可以了解更多信息。

...用于可变参数函数(append就是一个例子),用于传递前面变量的所有元素。

因此,给定一个变量x := []int{1, 2, 3},表达式foo(x...)将把它作为参数传递给函数,就好像你调用了foo(1, 2, 3),而foo(x)相当于foo([]int{1, 2, 3})

英文:

> The append built-in function appends elements to the end of a slice.

Read more in the docs.

The ... is used in variadic functions (of which append is an example), to pass all of the elements of the preceding variable.

So given a variable x := []int{1, 2, 3}, the expression foo(x...) will pass it to a function as if you had called foo(1, 2, 3) in contrast to foo(x) which would equivalent to foo([]int{1, 2, 3}).

答案2

得分: 1

基本上,append 函数接受 options 切片,将额外的选项追加到其中,返回新的切片,然后通过 ... 将这个合并后的切片作为单独的参数传递给 kithttp.NewServer 构造函数。

英文:

Basically append takes the options slice, appends additional options to it, returns new slice and then this merged slice is passed as separate arguments to kithttp.NewServer constructor thanks to ....

huangapple
  • 本文由 发表于 2017年7月13日 17:39:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/45076887.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定