Search code examples
goinitializer-list

What is the Go equivalent of C++ initializer lists?


In C++, I might do the following:

for (const string& key : {"foo", "bar", "baz"}) {
  DoSomeThingWithKey(key);
}

The {"foo", "bar", "baz"} is a std:initializer_list. Awesomeness.

Is there an equivalent idiomatic pattern for Go?


Solution

  • Simply use a slice:

    for _, value := range []string{"foo", "bar", "baz"} {
        fmt.Println(value)
    }
    

    or alternatively an array:

    for _, value := range [...]string{"foo", "bar", "baz"} {
        fmt.Println(value)
    }