如何比较结构体切片。

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

How to compare slice of struct

问题

  1. type RecordProxy struct {
  2. Amt int `csv:"Amt"`
  3. Descr string `csv:"Descr"`
  4. Date string `csv:"Date"`
  5. ID string `csv:"ID"`
  6. }
  7. type RecordSource struct {
  8. Date string `csv:"Date"`
  9. ID string `csv:"ID"`
  10. Amount int `csv:"Amount"`
  11. Description string `csv:"Description"`
  12. }

我有一个 []RecordProxy[]RecordSource 的结构体切片,我想检查这两个结构体切片是否相等。

你有什么想法吗?

英文:
  1. type RecordProxy struct {
  2. Amt int `csv:"Amt"`
  3. Descr string `csv:"Descr"`
  4. Date string `csv:"Date"`
  5. ID string `csv:"ID"`
  6. }
  7. type RecordSource struct {
  8. Date string `csv:"Date"`
  9. ID string `csv:"ID"`
  10. Amount int `csv:"Amount"`
  11. Description string `csv:"Description"`
  12. }

i have a slice of struct []RecordProxy and []RecordSource
i want to check if this 2 slice of struct is equal.

do you have any idea?

答案1

得分: 2

如@mkopriva所评论的“你必须实现自己的自定义比较方式”,即根据两个切片的规则来确定它们是否相等。

这只是一个示例:

  1. func CompareRecords(a []RecordProxy, b []RecordSource) bool {
  2. lengthA, lengthB := len(a), len(b)
  3. if lengthA != lengthB {
  4. return false
  5. }
  6. for i := range a {
  7. // 定义自己的不相等规则:
  8. if a[i].Amt != b[i].Amount ||
  9. // 结构体字段的其他规则...
  10. a[i].Date != b[i].Date {
  11. return false
  12. }
  13. }
  14. return true
  15. }
英文:

As @mkopriva comments "you have to implement your own custom way of comparing", i.e. tell what rules to according to the two slices could be considered equal.

Only an example:

  1. func CompareRecords(a []RecordProxy, b []RecordSource) bool {
  2. lengthA, lengthB := len(a), len(b)
  3. if lengthA != lengthB {
  4. return false
  5. }
  6. for i := range a {
  7. // define your own unequal rules:
  8. if a[i].Amt != b[i].Amount ||
  9. // other rules for fields of structs...
  10. a[i].Date != b[i].Date {
  11. return false
  12. }
  13. }
  14. return true
  15. }

答案2

得分: 0

比较结构体切片(a、b)的更好方法是使用反射:

  1. if len(a) != len(b) {
  2. return false
  3. }
  4. flag := true
  5. for i := 0; i < len(a); i++ {
  6. if reflect.DeepEqual(a[i], b[i]) {
  7. flag = true
  8. } else {
  9. flag = false
  10. }
  11. }
  12. // 验证 flag
  13. if flag == false {
  14. return false
  15. } else {
  16. return true
  17. }

请注意,这段代码存在一些错误,我只是按照你提供的内容进行了翻译。

英文:

the better way to compare slice of structs ( a, b) is using reflect if

  1. if len(a) != len(b) {
  2. return false
  3. }
  4. flag := true
  5. for i:=0; len(a); i++{
  6. if reflect.DeepEqual(a[i], b[i]) {
  7. falg = true
  8. } else {
  9. flag = flase
  10. }
  11. }
  12. //verify flag
  13. if flag == false{
  14. return false
  15. } else {
  16. return true
  17. }

huangapple
  • 本文由 发表于 2021年11月11日 12:39:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/69923263.html
匿名

发表评论

匿名网友

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

确定