I wrote an article in the hope that it will be of benefit to those who are starting Go. When I first saw "..." in the source code, there aren't many information in Japanese even if I googled it, so I will summarize how to use "..." that I often use in business. I thought about it.
Understand how to use "..." and the points
People who don't understand Go's "..."
Function parameters can be variable length. For example, if you have a function that wants to receive multiple ints in a variable way, you can write: The point is to write ... before the type, like ** ... int **.
//WriteInt is a function that receives and outputs a variable int
func WriteInt(nums ...int) {
for _, v := range nums {
fmt.Println(v)
}
}
When executed, the result is as follows
func main() {
WriteInt(1, 2, 3)
}
//Execution result
1
2
3
You can pass the variable-length argument function explained in the previous chapter at once by using "...". The point is to write ... after the value you want to pass, such as ** s ... **.
func main() {
s := []int{1, 2, 3}
//The value that s has...All passed to WriteInt using
WriteInt(s...)
}
func WriteInt(nums ...int) {
for _, v := range nums {
fmt.Println(v)
}
}
It is also useful when appending a slice.
func main() {
s1 := []int{1, 2, 3}
s2 := []int{4, 5, 6}
s3 := append(s1, s2...)
fmt.Println(s3)
}
//Execution result
[1 2 3 4 5 6]
Official Document Passing_arguments_to ... parameters Official document append 3 dots in 4 places Expand and pass slices to variadic functions with Go ★ Ultimate Guide to Go Variadic Functions
Recommended Posts