go 结构体列表比较是否相等

使用reflect的DeepEqual方法

场景1:结构体列表按顺序匹配(直接比较)

package main

import (
	"fmt"
	"reflect"
)

type Student struct {
	Age   int
	Score int
}

func main() {
	s1 := []Student{
		{Age: 1, Score: 10},
		{Age: 2, Score: 20},
		{Age: 3, Score: 30},
	}
	s2 := []Student{
		{Age: 1, Score: 10},
		{Age: 2, Score: 20},
		{Age: 3, Score: 30},
	}
	fmt.Println(reflect.DeepEqual(s1, s2))

	s3 := []Student{
		{Age: 1, Score: 10},
		{Age: 2, Score: 20},
		{Age: 3, Score: 30},
	}
	s4 := []Student{
		{Age: 3, Score: 30},
		{Age: 1, Score: 10},
		{Age: 2, Score: 20},
	}
	fmt.Println(reflect.DeepEqual(s3, s4))
}

场景2:结构体列表不按顺序匹配(用map比较)

package main
 
import (
	"fmt"
	"reflect"
)
 
type Student struct {
	Age   int
	Score int
}
 
func compare(a, b []Student) bool {
	am := make(map[Student]bool, len(a))
	for _, s := range a {
		am[s] = true
	}
	bm := make(map[Student]bool, len(b))
	for _, s := range b {
		bm[s] = true
	}
	return reflect.DeepEqual(am, bm)
}
 
func main() {
	s1 := []Student{
		{Age: 1, Score: 10},
		{Age: 2, Score: 20},
		{Age: 3, Score: 30},
	}
	s2 := []Student{
		{Age: 1, Score: 10},
		{Age: 2, Score: 20},
		{Age: 3, Score: 30},
	}
	fmt.Println(compare(s1, s2))
 
	s3 := []Student{
		{Age: 1, Score: 10},
		{Age: 2, Score: 20},
		{Age: 3, Score: 30},
	}
	s4 := []Student{
		{Age: 3, Score: 30},
		{Age: 1, Score: 10},
		{Age: 2, Score: 20},
	}
	fmt.Println(compare(s3, s4))
}

posted on 2024-08-28 21:15  王景迁  阅读(22)  评论(0)    收藏  举报

导航