'Difference between initialization of struct slices

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)



Solution 1:[1]

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

Solution 2:[2]

type PersonInfo is an object of Person, while PersonInfo2 is a class (or type in Golang) by itself. Even though their data structure is similar.

So, when you run DeepEqual() to check the similarity it will turn out to be false.

Example by previous comment:

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

Hope this helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Kingsley Tan