7

let's say I have a slice of anonymous structs

data := []struct{a string, b string}{}

Now, I would like to append a new item to this slice.

data = append(data, ???)

How do I do that? Any ideas?

apxp
  • 5,240
  • 4
  • 23
  • 43
Yuri Dosovitsky
  • 121
  • 1
  • 6
  • 3
    Possible duplicate of [Initialize nested struct definition in Golang](https://stackoverflow.com/questions/26866879/initialize-nested-struct-definition-in-golang) – Peter Aug 12 '18 at 12:21

2 Answers2

16

Since you're using an anonymous struct, you have to again use an anonymous struct, with identical declaration, in the append statement:

data = append(data, struct{a string, b string}{a: "foo", b: "bar"})

Much easier would be to use a named type:

type myStruct struct {
    a string
    b string
}

data := []myStruct{}

data = append(data, myStruct{a: "foo", b: "bar"})
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
0

Actually, I found a way to add elements to array without repeated type declaration. But it is dirty.

    slice := []struct {
        v, p string
    }{{}} // here we init first element to copy it later

    el := slice[0]

    el2 := el   // here we copy this element
    el2.p = "1" // and fill it with data
    el2.v = "2"

    // repeat - copy el as match as you want

    slice = append(slice[1:], el2 /* el3, el4 ...*/) // skip first, fake, element and add actual

Slice of pointers to struct is more conventional. At that case coping will slightly differ

    slice := []*struct { ... }{{}}
    el := slice[0]
    el2 := *el

All this is far from any good practices. Use carefully.

Alexus1024
  • 447
  • 5
  • 7