25

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?

1 Answer 1

52

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.

Sign up to request clarification or add additional context in comments.

3 Comments

How about this? It has more values and not working for another reason. Can't figure out
If you don't name your fields in the literal notation, you have to provide a value for all fields, otherwise name the field. golang.org/ref/spec#Composite_literals . Working example based on yours: play.golang.org/p/13OSJHd5xe
Note that you don't need the second Example - go is smart enough to figure out that an []Example is full of Example items without explicitly naming them. Playground

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.