比较两个类似数组的结构体在Go语言中的方法。

huangapple go评论85阅读模式
英文:

Compare two structs like array in golang

问题

我正在尝试在Golang中比较两个数组类型的结构体,以判断从网页抓取得到的struct1是否与从数据库获取的struct2相等。这是我想到的一种方法,可以知道外部网页和我的数据库之间是否发生了变化。

结构体定义如下:

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

从抓取的结果如下:

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

从网页获取的结果如下:

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

我的代码如下:

fmt.Println(exchanges)
dbExchanges := getExchangesFromDB()
fmt.Println(dbExchanges)
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

英文:

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:

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

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

Result:
no is equal

Struct equal: false

答案1

得分: 1

在第一个if语句中,你正在比较两个变量的内存地址,而不是它们的值。在第二个if语句中(使用reflect.DeepEqual),你正在比较它们的值。

英文:

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.

huangapple
  • 本文由 发表于 2022年11月19日 07:42:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/74496379.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定