如何在 Go 中比较结构与嵌套切片,不考虑元素顺序
时间:2024-02-04
浏览:442
作者:佚名
有志者,事竟成!如果你在学习Golang,那么本文《如何在 Go 中比较结构与嵌套切片,不考虑元素顺序》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~
问题内容
给出下一个类型结构定义:
type A struct {
Id int
Bs []B
Sub C
}
type B struct {
Id int
Str string
}
type C struct {
Id int
Ds []D
}
type D struct {
Id int
Num int
}
我想测试 A 的接下来两个实例在语义上是否相等,无论所有层次结构级别中切片元素的顺序如何。
var want = &A{
Id: 1,
Bs: []B{{Id: 10, Str: "b10"}, {Id: 20, Str: "b20"}},
Sub: C{
Id: 100,
Ds: []D{{Id: 101, Num: 1001}, {Id: 102, Num: 1002}},
},
}
var got = &A{
Id: 1,
Bs: []B{{Id: 20, Str: "b20"}, {Id: 10, Str: "b10"}},
Sub: C{
Id: 100,
Ds: []D{{Id: 102, Num: 1002}, {Id: 101, Num: 1001}},
},
}
断言比较应返回true
正确答案
包 cmp 旨在成为 reflect.DeepEqual 的更强大、更安全的替代品用于比较两个值在语义上是否相等。
这里是语义相等结构比较的完整实现,无论切片元素在所有层次结构级别的顺序如何。
文件source.go
package main
type A struct {
Id int
Bs []B
Sub C
}
type B struct {
Id int
Str string
}
type C struct {
Id int
Ds []D
}
type D struct {
Id int
Num int
}
func NewA() *A {
return &A{
Id: 1,
Bs: []B{{Id: 20, Str: "b20"}, {Id: 10, Str: "b10"}},
Sub: C{
Id: 100,
Ds: []D{{Id: 102, Num: 1002}, {Id: 101, Num: 1001}},
},
}
}
文件source_test.go
package main
import (
"fmt"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
)
var want = &A{
Id: 1,
Bs: []B{{Id: 10, Str: "b10"}, {Id: 20, Str: "b20"}},
Sub: C{
Id: 100,
Ds: []D{{Id: 101, Num: 1001}, {Id: 102, Num: 1002}},
},
}
func TestNewA(t *testing.T) {
got := NewA()
less := func(x, y any) bool {
switch xv := x.(type) {
case B:
yv := y.(B)
return fmt.Sprintf("%d-%s", xv.Id, xv.Str) < fmt.Sprintf("%d-%s", yv.Id, yv.Str)
case D:
yv := y.(D)
return fmt.Sprintf("%d-%d", xv.Id, xv.Num) < fmt.Sprintf("%d-%d", yv.Id, yv.Num)
default:
return false
}
}
if diff := cmp.Diff(want, got, cmpopts.SortSlices(less)); diff != "" {
t.Errorf("mismatch:\n%s", diff)
}
}本篇关于《如何在 Go 中比较结构与嵌套切片,不考虑元素顺序》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
站内热门
最新文章
12.01
热门专题
