chai2010/advanced-go-programming-book

Ch 1.4.1, 2nd example is kind of misleading, which says "more ...int 对应 []int 切片类型" before variadic function definition

Tang7 opened this issue · 0 comments

Tang7 commented

Inside of the variadic function, func Sum(a int, more ...int), more is a slice of int, []int. Since it is the compiler converts the variadic parameters into a slice of type int.

But when defining the variadic function, it is incorrect to claim more ...int int 对应 []int 切片类型.
Tyring Sum(1, []int{2,3,4}) causes a stack overflow error. Since more is already a slice and compiler tries to create a new slice from []int, which is an invalid behavior, instead, it will cause the compiler eat up all the stack until overflow.

Therefore, the correct way to pass a slice into a variadic function is Sum(1, []int{2,3,4}...), which unpacks the slice to fit variadic parameters.

The 3rd example is also kind of misleading. Yes, it works, but it is not needed to unpack a slice of empty interface when using fmt.Println

var a = []interface{}{123, "abc"}
fmt.Println(a)

will also print [123, abc], because it is an empty interface.

These two examples are inappropriate to show the feature of variadic parameters, interface type and unpack in golang. The example only basically show the code works, but lack of thoughtful explanation how and why they are work. Which are misleading as I explained above.