Difference Between []String and ...String in Go

Jay Singh Jan 30, 2023
  1. Define a Slice Using []string in Go
  2. Define a Variadic Function Using ...string in Go
  3. Use Both []string and ...string in Go
Difference Between []String and ...String in Go

An array section is referred to as a slice. Slices provide more power, flexibility, and convenience than arrays.

Slices are indexable and have a length, much like arrays. Unlike arrays, they can be expanded.

A slice is a data structure that defines a contiguous section of an array and is kept separately from the slice variable.

An array is not the same as a slice. A slice of an array is a subset of it.

This article will discuss the differences between []string and ...string in Go.

Define a Slice Using []string in Go

In this example, we used the for and range commands to iterate through a set of words.

package main

import "fmt"

func main() {
	words := []string{"Iron Man", "Thor", "Hulk", "Dr Strange", "Spiderman"}
	for idx, word := range words {
		fmt.Println(idx, word)
	}
}

Output:

0 Iron Man
1 Thor
2 Hulk
3 Dr Strange
4 Spiderman

Define a Variadic Function Using ...string in Go

An ellipsis (...) in front of the parameter defines a variadic function. Let’s make a program that responds to Avengers names being supplied to a function.

We designed a sayHello method that accepts one parameter, names. Since we added an ellipsis (...) before the data type: ...string, the argument is a variable.

Go understands that the function can take zero, one, or many parameters.

The names parameter is sent to the sayHello method as a slice. Because the data type is a string, the names parameter can be handled inside the method body like a slice of strings ([]string).

We can use the range operator to build a loop that iterates across the slice of strings.

package main

import "fmt"

func main() {
    sayHello()
    sayHello("Iron Man")
    sayHello("Thor", "Hulk", "Dr Strange", "Spiderman")
}

func sayHello(names ...string) {
    for _, n := range names {
        fmt.Printf("Hello %s\n", n)
}

Output:

Hello Iron Man
Hello Thor
Hello Hulk
Hello Dr Strange
Hello Spiderman

Use Both []string and ...string in Go

package main

import "fmt"

func f(args ...string) {
	fmt.Println(len(args))
	for i, s := range args {
		fmt.Println(i, s)
	}
}

func main() {
	args := []string{"Hello", "Jay"}
	f(args...)
}

Output:

2
0 Hello
1 Jay

Related Article - Go Slice

Related Article - Go Variadic