Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding anonymous struct element to slice

Tags:

go

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?

like image 902
Yuri Dosovitsky Avatar asked Aug 12 '18 12:08

Yuri Dosovitsky


1 Answers

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"})
like image 95
Flimzy Avatar answered Nov 05 '22 02:11

Flimzy