How to use Ellipsis (…) in Golang?


Ellipsis (...) is a special syntax in Golang that allows developers to pass a variable number of arguments to a function. This can be extremely useful when working with functions that require a variable number of arguments, such as print statements or string concatenation. In this article, we will discuss how to use ellipsis in Golang and provide some practical examples.

Understanding Ellipsis in Golang

Ellipsis (...) is a syntax that allows developers to pass a variable number of arguments to a function. This syntax is used in the function signature and indicates that the function can take any number of arguments of the same type. For example, the following function signature uses the ellipsis syntax to indicate that it can take any number of integers as arguments −

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

Using Ellipsis in Function Calls

When calling a function that uses the ellipsis syntax, you can pass any number of arguments of the specified type. For example, the following code calls the sum function with three integers −

sum(1, 2, 3)

You can also call the same function with an arbitrary number of integers, as shown in the following example −

sum(1, 2, 3, 4, 5, 6)

Using Ellipsis with Slices

Ellipsis can also be used with slices in Golang. When used in this context, it is known as a variadic slice. The syntax for using a variadic slice is similar to using ellipsis in a function signature. For example, the following function uses a variadic slice to concatenate a variable number of strings −

func concatenateStrings(strings ...string) string {
   return strings.Join(strings, " ")
}

You can call this function with any number of strings, as shown in the following example −

concatenateStrings("Hello", "World")
concatenateStrings("Hello", "to", "the", "World")

Using Ellipsis with Interfaces

Ellipsis can also be used with interfaces in Golang. When used in this context, it is known as a variadic interface. The syntax for using a variadic interface is similar to using ellipsis in a function signature. For example, the following function uses a variadic interface to print a variable number of values −

func printValues(values ...interface{}) {
   for _, value := range values {
      fmt.Println(value)
   }
}

You can call this function with any number of values, as shown in the following example −

printValues("Hello", 42, true)
printValues(1, 2, 3, 4, 5)

Conclusion

Ellipsis (...) is a powerful syntax in Golang that allows developers to pass a variable number of arguments to a function. This syntax can be used with functions, slices, and interfaces, making it a versatile tool for any developer. By understanding how to use ellipsis in Golang, you can write more efficient and flexible code.

Updated on: 25-Apr-2023

821 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements