官术网_书友最值得收藏!

variadic.go

In order to understand the first set of tests, we need to understand what a variadic function is and how Go handles it. Let's start with the definition:

Variadic function is a function that can accept any number of arguments during function call.

Given that Go is a statically typed language, the only limitation imposed by the type system on a variadic function is that the indefinite number of arguments passed to it should be of the same data type. However, this does not limit us from passing other variable types. The arguments are received by the function as a slice of elements if arguments are passed, else nil, when none are passed.

Let's look at the code to get a better idea:

// variadic.go 
 
package main 
 
func simpleVariadicToSlice(numbers ...int) []int { 
   return numbers 
} 
 
func mixedVariadicToSlice(name string, numbers ...int) (string, []int) { 
   return name, numbers 
} 
 
// Does not work. 
// func badVariadic(name ...string, numbers ...int) {} 

We use the ... prefix before the data type to define a functions as a variadic function. Note that we can have only one variadic parameter per function and it has to be the last parameter. We can see this error if we uncomment the line for badVariadic and try to test the code.

主站蜘蛛池模板: 铜陵市| 霞浦县| 兖州市| 永济市| 磐石市| 临沧市| 吴忠市| 博湖县| 扎赉特旗| 克什克腾旗| 左贡县| 乌兰察布市| 宁晋县| 竹溪县| 徐闻县| 日照市| 陕西省| 伊通| 兴仁县| 阳江市| 高要市| 麟游县| 龙门县| 峨眉山市| 西乌珠穆沁旗| 连平县| 德安县| 南投县| 奈曼旗| 巫山县| 三门峡市| 九寨沟县| 衡东县| 新乡县| 龙海市| 金湖县| 四子王旗| 深圳市| 寻甸| 巴楚县| 博乐市|