如何在语义上比较带有嵌套切片的结构,而不管Go中元素的顺序如何

sg2wtvxw  于 5个月前  发布在  Go
关注(0)|答案(1)|浏览(52)

给定下一个类型结构定义:

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}},
    },
}


assert比较应该返回true

4szc88ey

4szc88ey1#

cmp旨在成为reflect.DeepEqual的更强大和更安全的替代品,用于比较两个值在语义上是否相等。
这里是语义相等结构比较的完整实现,而不管切片元素在所有层次结构级别上的顺序。

文件源.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)
    }
}

相关问题