user2671513
user2671513

Reputation:

Go, Golang : array type inside struct, missing type composite literal

I need to add slice type to this struct.

 type Example struct {
    text  []string
 }

 func main() {
    var arr = []Example {
        {{"a", "b", "c"}},
    }
    fmt.Println(arr)    
 }

Then I am getting

  prog.go:11: missing type in composite literal
  [process exited with non-zero status]

So specify the composite literal

    var arr = []Example {
         {Example{"a", "b", "c"}},

But still getting this error:

    cannot use "a" (type string) as type []string in field value

http://play.golang.org/p/XKv1uhgUId

How do I fix this? How do I construct the struct that contains array(slice) type?

Upvotes: 25

Views: 67167

Answers (1)

Kavu
Kavu

Reputation: 8374

Here is your proper slice of Example struct:

[]Example{
  Example{
   []string{"a", "b", "c"},
  },
}

Let me explain it. You want to make a slice of Example. So here it is — []Example{}. Then it must be populated with an ExampleExample{}. Example in turn consists of []string[]string{"a", "b", "c"}. It just the matter of proper syntax.

Upvotes: 52

Related Questions