简体   繁体   中英

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?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM