Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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 Answers

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.

like image 159
Kavu Avatar answered Sep 13 '25 07:09

Kavu