首页 > 其他分享 >go 结构体列表比较是否相等

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

时间:2024-08-28 21:15:45浏览次数:7  
标签:10 相等 20 Age 30 列表 Score Student 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))
	bm := make(map[Student]bool, len(b))
	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))
}

标签:10,相等,20,Age,30,列表,Score,Student,go
From: https://www.cnblogs.com/WJQ2017/p/18385552

相关文章