這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
1. 用於數組: 表示長度與元素個數相同.
在golang中數組的長度是類型的一部分,不同長度,不同類型.
2. 用於參數: 用於形參表示可變參數. 用於實參表示直接傳遞. 具體解釋參數見官方文檔:
傳遞可變參數時:
(1) 如果實參後不跟..., 則在底層建立與形參類型相同的slice,然後將實參賦值後傳遞.
(2) 如果實參後跟..., 則不在底層建立與形參類型相同的slice,而是直接將實參傳遞給形參.
/ref/spec#Passing_arguments_to_..._parameters
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. The length and capacity of the slice is therefore the number of arguments bound to p and may differ for each call site.
Given the function and calls
func Greeting(prefix string, who ...string)
Greeting("nobody")
Greeting("hello:", "Joe", "Anna", "Eileen")
within Greeting, who will have the value nil in the first call, and []string{"Joe", "Anna", "Eileen"} in the second.
If the final argument is assignable to a slice type []T, it may be passed unchanged as the value for a ...T parameter if the argument is followed by .... In this case no new slice is created.
Given the slice s and call
s := []string{"James", "Jasmine"}Greeting("goodbye:", s...)
within Greeting, who will have the same value as s with the same underlying array.