Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between initialization of struct slices

Tags:

arrays

struct

go

type Person struct {
    ID int `json:"id"`
}

type PersonInfo []Person

type PersonInfo2 []struct {
   ID int `json:"id"`
}

Is there have difference between PersonInfo (named slice of named structs) and PersonInfo2 (named slice of unnamed structs)

like image 786
Blue Joy Avatar asked Aug 29 '26 11:08

Blue Joy


2 Answers

The main difference is how you have to initialize Person objects outside of the PersonInfo/PersonInfo2 initialization. Since PersonInfo2 is an array of the anonymous struct type we know nothing about this type outside of the PersonInfo2 initialization.

So they can both be initialized like this:

m := PersonInfo{{1}, {2}}
n := PersonInfo2{{1},{2}}

However if we want to append an element of the anonymous struct type we would have to specify the full type:

append(n, struct { ID int  `json:"id"` }{3})

If we print these out we can see they appear to be the same: fmt.Printf("%+v\n%+v", m, n) Outputs:

[{ID:1} {ID:2}]
[{ID:1} {ID:2}]

However they wont be deeply equal because PersonInfo is an array of type Person and PersonInfo2 is an array of anonymous struct type. So the following:

if !reflect.DeepEqual(m,n) {
    print("Not Equal")
}

will print "Not Equal".

Here is a link to see for yourself.

When appending to PersonInfo2 we have to repeat the anonymous struct type for every value we want to append, it is probably better to use PersonInfo as an array of type Person.

like image 181
Jack Avatar answered Sep 01 '26 06:09

Jack


Go is using structural typing, that means, as long as the two types have the same underlying type, they are equivalent.

So, for your question: Person and struct{ ID int 'json:"id"'} is equivalent because they have the same underlying type, and therefore, PersonInfo and PersonInfo2 are also equivalent. I took of the json tags to simplify the example.

person1 := Person{1}

pStruct1 := struct{ID int}{2}


pInfo1 := PersonInfo{
    person1,
    pStruct1,
}

pInfo2 := PersonInfo2{
    person1,
    pStruct1,
}


fmt.Printf("%+v\n", pInfo1)
fmt.Printf("%+v", pInfo2);

//outputs
//PersonInfo: [{ID:1} {ID:2}]
//PersonInfo2: [{ID:1} {ID:2}]

Code example: https://play.golang.org/p/_wlm_Yfdy2

like image 27
stevenferrer Avatar answered Sep 01 '26 06:09

stevenferrer