golang 語法糖 ...

go 語言是google 開發的一種靜態強類型、編譯型、併發型,並具有垃圾回收功能的編程語言。2009年11月正式宣佈推出,在2016年,Go被軟件評價公司TIOBE 選為TIOBE 2016 年最佳語言

go語言簡潔的語法和內存安全以及併發計算深受互聯網公司的青睞。下面就介紹其中的一個簡潔的語法糖 ...

... 作為go語言的語法糖,主要有下面兩種用法

  • 作為函數的可變參數,表示可以接受任意個數但是相同類型的參數
<code>

package

main

import

(

"fmt"

"reflect"

)

func

print

(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"

}

print

(

"A"

,

"B"

,

"C"

)

print

(users...)

print

() } /<code>

運行上面代碼打印如下:

<code>type 

is

: []

string

zhangsan lisi wangwu zhaoliu type

is

: []

string

A B C type

is

: []

string

/<code>

由上面一段代碼可以看出,print函數的參數定義為...string 類型 第一次調用的時候傳入的是三個字符常量,打印出的who 類型為[]string。

也就是...T 類型等價於[]T 類型

在官方文檔上有這麼一段描述

<code>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. /<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 中。


分享到:


相關文章: