Slabgorb
Slabgorb

Reputation: 816

What is the meaning of [...] in a (slice) variable initializer in golang?

I was browsing the stdlib, specifically https://golang.org/src/html/template/context.go and I came across this code, which is tasked with making string representations of a uint8 enum defined previously.

var stateNames = [...]string{
    stateText:        "stateText",
    stateTag:         "stateTag",
//... many more elided 
    stateCSSBlockCmt: "stateCSSBlockCmt",
    stateCSSLineCmt:  "stateCSSLineCmt",
    stateError:       "stateError",
  }

I was interested in the [...] syntax of the initializer. Is there something that means more than a simple var stateNames = []string{} in that syntax?

Upvotes: 1

Views: 813

Answers (1)

Slabgorb
Slabgorb

Reputation: 816

Ok, as I should have done, I put this in the playground, initialized the variable, then called fmt.Printf("%T", stateNames), and got [25]string

https://play.golang.org/p/3k-WiI8Jh9K

Turns out, this defines an array, not a slice, and the array is initialized with the length automatically set to the number of items defined. Neat!

Upvotes: 5

Related Questions