

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 3
click for more info
Not enough gems
Cost: 6 gems
1: Arrays in Go
incomplete
2: Slices in Go
incomplete
3: Slices Review
incomplete
4: Make
incomplete
5: Len and Cap Review
incomplete
6: Variadic
incomplete
7: Append
incomplete
8: Range
incomplete
9: Slice of Slices
incomplete
10: Tricky Slices
incomplete
11: Message Filter
incomplete
12: Password Strength
incomplete
13: Message Tagger
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Functions can take an arbitrary number of final arguments. This is done using the ... syntax in the function signature.
A variadic function receives the variadic arguments as a slice.
func concat(strs ...string) string {
final := ""
// strs is just a slice of strings
for i := 0; i < len(strs); i++ {
final += strs[i]
}
return final
}
func main() {
final := concat("Hello ", "there ", "friend!")
fmt.Println(final)
// Output: Hello there friend!
}
The familiar fmt.Println() and fmt.Sprintf() are variadic, as are many in the standard library! fmt.Println() prints each element with space delimiters and a newline at the end.
func Println(a ...interface{}) (n int, err error)
The spread operator allows us to pass a slice into a variadic function. The spread operator consists of three dots following the slice in the function call.
func printStrings(strings ...string) {
for i := 0; i < len(strings); i++ {
fmt.Println(strings[i])
}
}
func main() {
names := []string{"bob", "sue", "alice"}
printStrings(names...)
}
We need to sum up the costs of all individual messages so we can send an end-of-month bill to our customers.
Complete the sum function to return the sum of all inputs.
Take note of how the variadic inputs and the spread operator are used in the test suite.