Compare two structs like array in golang


I am trying to compare 2 structs of the array type in Golang in order to know if having struct1 obtained from web scrapping is equal to struct 2, which is data fetched from the database.
It is the way that I have thought to be able to know if there has been a change between the external web and my database.

The structs is:

type Exchange struct {
    Name          string    `gorm:"Column:name" json:"name"`
    Buy           float64   `gorm:"Column:buy" json:"buy"`
    Sell          float64   `gorm:"Column:sell" json:"sell"`

The result after consult is from scrapping:

&[{Dólar 38.5  41 } {Euro 38.82  43.57 } {P. Argentino 0.05  0.35 } {Real 6.95  8.95 }]

From web

&[{Dólar 38.5 41} {Euro 38.82 43.57} {P. Argentino 0.05 0.35} {Real 6.95 8.95}]

My Code:

    dbExchanges := getExchangesFromDB()
    if exchanges == dbExchanges {
        fmt.Println("is equal")
    } else {
        fmt.Println("no is equal")

    fmt.Println("Struct equal: ", reflect.DeepEqual(exchanges, dbExchanges))

no is equal

Struct equal: false


In the first if you are comparing the memory address of the two variables instead of theirs values. In the second if clause (using reflect.DeepEqual) you are comparing their values.

Answered By – ilan

Answer Checked By – Willingham (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.