go 語言是google 開發的一種靜態強類型、編譯型、併發型,並具有垃圾回收功能的編程語言。2009年11月正式宣佈推出,在2016年,Go被軟件評價公司TIOBE 選為TIOBE 2016 年最佳語言
go語言簡潔的語法和內存安全以及併發計算深受互聯網公司的青睞。下面就介紹其中的一個簡潔的語法糖 ...
... 作為go語言的語法糖,主要有下面兩種用法
- 作為函數的可變參數,表示可以接受任意個數但是相同類型的參數
<code>package
mainimport
("fmt"
"reflect"
)func
(who ...
string
) { fmt.Println("type is :"
, reflect.TypeOf(who))for
_, v :=range
who { fmt.Printf("%v\t"
, v) } fmt.Println(""
) }func
main
()
{ users := []string
{"zhangsan"
,"lisi"
,"wangwu"
,"zhaoliu"
}"A"
,"B"
,"C"
)
運行上面代碼打印如下:
<code>typeis
: []string
zhangsan lisi wangwu zhaoliu typeis
: []string
A B C typeis
: []string
/<code>
由上面一段代碼可以看出,print函數的參數定義為...string 類型 第一次調用的時候傳入的是三個字符常量,打印出的who 類型為[]string。
也就是...T 類型等價於[]T 類型
在官方文檔上有這麼一段描述
<code>If f is variadicwith
afinal
parameter pof
type
...T,then
within
f thetype
of
pis
equivalentto
type
[]T.If
fis
invokedwith
no
actual argumentsfor
p, thevalue
passedto
pis
nil. Otherwise, thevalue
passedis
anew
sliceof
type
[]Twith
anew
underlyingarray
whose successive elementsare
the actual arguments, whichall
must be assignableto
T. Thelength
and
capacity
of
the sliceis
therefore thenumber
of
argumentsbound
to
pand
may differfor
each
call
site. /<code>
當print 不傳遞參數時,who的值為nil,類型還是[]string, 如第3處調用
如上代碼第2處print調用就是將切片打散,然後作為不定參數傳入...sting,也就是下面的第二個用處
- 將切片打散
我們常用的append函數定義就是採用了 ...
append(s S, x ...T) S // T is the element type of S
<code>src := []int
{1
,2
,3
} dst := []int
{0
} dst =append
(dst, src...) /<code>
如上代碼,將切片src的元素打散傳入dst 中。