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

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.

主站蜘蛛池模板: 长宁县| 华宁县| 抚松县| 霍邱县| 昌江| 吉安县| 南郑县| 泰宁县| 曲松县| 阿瓦提县| 长岛县| 平果县| 东山县| 锦屏县| 霸州市| 杭州市| 天峨县| 延川县| 呼图壁县| 基隆市| 乌鲁木齐市| 东辽县| 大同县| 故城县| 棋牌| 裕民县| 陵水| 屏南县| 新巴尔虎左旗| 绥宁县| 荔浦县| 铅山县| 天台县| 陇川县| 许昌市| 平谷区| 隆安县| 手游| 民权县| 依兰县| 读书|