15

In the go lang spec they used three dots in one of the examples:

days := [...]string{"Sat", "Sun"}  // len(days) == 2

Does it make any difference if the three dots are left out?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Rusty Rob
  • 16,489
  • 8
  • 100
  • 116

1 Answers1

31

It makes a pretty big difference: The difference is between an array and a slice.

[]string creates a slice that points to an array of strings. On the other hand, [...] creates an actual array of strings.

There is a great blog post about the difference between the two on the golang blog. I'll try to summarize here as best I can.

Arrays in golang are like value types, they are references to a specific type and are always of a specific length. There are two ways to create an array: 1) with explicit length and 2) implicit length:

// Explicit length. 
var days := [7]string { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }

// Implicit length. (Let the compiler figure it out how long it is)
var days := [...]string { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" } 

These are both equivalent array definitions. Note that the length of an array is part of it's type definition. So, you can't interchange arrays of similar type with different lengths:

// These two are not interchangeable!
var someArray [5]string;
var otherArray [10]string;

func work(data [5]string) { /* ... */ }

work(someArray)  // good
work(otherArray) // not so good

Also note that arrays, like structs, are passed as value – a copy of the array will be given to a function, not a reference to it..

Slices, on the other hand, are like reference types. They are backed by an array, but they are more malleable. They include a pointer to a position within array, a length, and a capacity.

// Create a slice
var days := []string { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }

Slices, unlike arrays, are not explicitly bound to their length and slices of different lengths can be passed for one another. They also act more like a pointer, which means they get passed by reference, instead of value.

There is also a great post about Go Data Structures, and how they are they are represented in memory. I highly recommend checking it out.

J. Holmes
  • 18,466
  • 5
  • 47
  • 52