Variadic functions in Go allow you to pass a variable number of arguments to a function. This is useful when you don't know in advance how many arguments you will pass. A variadic function in Golang accepts multiple arguments of the same type and can be called with any number of arguments, including none.

package main
import "fmt"
// Hàm Variadic tính tổng
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func main() {
fmt.Println("Sum of 1, 2, 3:", sum(1, 2, 3))
fmt.Println("Sum of 4, 5:", sum(4, 5))
fmt.Println("Sum of no numbers:", sum())
}
Result:
Sum of 1, 2, 3: 6
Sum of 4, 5: 9
Sum of no numbers: 0
Syntax:
func functionName(parameters ...Type) ReturnType {
// Code
}
In the above syntax:
parameters ...Typeindicates that the function can accept a variable number of arguments of type Type.
- You can access arguments in a function as a slice.
How to use uncertain functions in Golang
Using Variadic functions
When defining a variadic function, you specify the argument types followed by an ellipsis (...) as in the example above. Inside the function, these arguments can be thought of as a slice.
Calling a variadic function
You can call a variadic function with any number of arguments, including zero. The function treats the arguments as a slice.
For example:
package main
import "fmt"
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func main() {
fmt.Println("Sum of 1, 2, 3:", sum(1, 2, 3))
fmt.Println("Sum of 4, 5:", sum(4, 5))
fmt.Println("Sum of no numbers:", sum())
}
Result:
Sum of 1, 2, 3: 6
Sum of 4, 5: 9
Sum of no numbers: 0
Variadic function with different parameters
You can also combine variadic parameters with regular parameters in a function. Variadic parameters must always be the last parameter.
For example:
package main
import "fmt"
// Hàm Variadic tính tổng
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
// Hàm với tham số thông thường và variadic
func greet(prefix string, nums ...int) {
fmt.Println(prefix)
for _, n := range nums {
fmt.Println("Number:", n)
}
}
func main() {
greet("Sum of numbers:", 1, 2, 3)
greet("Another sum:", 4, 5)
greet("No numbers sum:")
}
Result:
Sum of numbers:
Number: 1
Number: 2
Number: 3
Another sum:
Number: 4
Number: 5
No numbers sum:
Limitations of Variadic functions
- Variadic functions can have only one variadic parameter and it must be the last parameter.
- You cannot have multiple variadic parameters in a single function definition.