简体   繁体   中英

Golang confusion with structs

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

type PersonInfo []Person

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

Is there have difference between PersonInfo and PersonInfo2

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.

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

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.

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