Mohamed Allam
Laravel Example

Laravel Example

Functions in Go: What are ... in Golang?

Functions in Go: What are ... in Golang?

In a short blog post, you will learn everything about ... three dots in Golang, how to write them or use them.

Mohamed Allam's photo
Mohamed Allam
·May 10, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Table of contents

  • Functions in Go: What are ... in Golang?
  • What is ... in Golang?
  • What are variadic functions
  • Under the hood
  • Slices and variadic

Functions in Go: What are ... in Golang?

golang variadic functions in golang.png

What is ... in Golang?

Many times when we write functions, we don’t have a determined number of arguments that we want to accept, one of the most familiar cases is the FMT package, specifically PrintF and its variants, they require at least one argument, but they can accept one or more number of function arguments

println("1","2","infinity")

What are variadic functions

Say hello to variadic functions, Go programming language functions that may be called with any number of arguments.

a quick example if within your shopping cart application, you need to sum the prices of items, and return the sum of type int. you will accept as many items as the user wants to buy.

func sum (prices... int) int {
    total := 0
    for _, price := range prices(
        total += price
    )
    return total
}

Then we can calculate the sum:


println(sum()) //0
println(sum(2)) //2
println(sum(1,2,5)) //8

Under the hood

Golang will read the values provided, and make of them a slice of integers []int as the parameter of the function

Implicitly the caller allocates an array, copies the arguments into it, and passes a slice of the entire array to the function.

We might have the slice created already, we can unpack it in our function call.

prices := []int{1,2,5}
println(sum(prices...))

Slices and variadic

Although we can see the parameters behave like a slice within the body of the function, its important to know variadic function is different than ordinary slice.

func varidic(...int){}
func notvaridic([]int){}

fmt.Printf("%T\n", varidic) // func(...int)
fmt.Printf("%T\n", notvaridic) // func([]int)

Full Source Code

 
Share this