atc0005 / learn

Various topics that I want to learn more about, either for professional development or for my own use
0 stars 0 forks source link

Golang | Variadic Expansion #18

Open atc0005 opened 5 years ago

atc0005 commented 5 years ago
package main

import "fmt"

func main() {

    names := []string{}
    names = append(names, "John")

    // Append multiple items at once
    names = append(names, "Sally", "George")

    // Append an entire slice to another slice
    moreNames := []string{"Bill", "Ginger", "Wilma"}
    names = append(names, moreNames...)

    fmt.Println(names)

}

The append function is looking for a string type as the second argument; without the trailing ... after moreNames the type passed would be []string and not string as required.

The instructor described the ... syntax as "exploding" the slice, presumably providing multiple string arguments in place of the one slice argument that would otherwise be provided.

atc0005 commented 5 years ago

https://gobyexample.com/variadic-functions

Additional example.

atc0005 commented 5 years ago

https://blog.learngoprogramming.com/golang-variadic-funcs-how-to-patterns-369408f19085#3f7e

The passed slice will be used inside the func; no new slice will be created.

This seems to imply that unlike passing in multiple individual arguments, this results in the slice "passing into" the function. So by-reference instead of by-value? Presumably much more efficient for a large amount of data.

atc0005 commented 5 years ago

https://medium.com/rungo/variadic-function-in-go-5d9b23f4c01a

append function expects the first argument to be a slice of type Type, while there can be a variable number of arguments after that. If we have a slice s2 that we want to append to a slice s1, how that will work?

As from append function syntax, we can’t pass another slice as an argument, it has to be one or many arguments of type Type. Hence, instead, we will use the unpack operator ... to unpack slice into the series of arguments (which is acceptable by append function).

and:

... signifies both pack and unpack operator but if three dots are in the tail position, it will unpack a slice.