简体   繁体   中英

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?

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.

Hope that helps.

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