1. With an attachment
One option is to group the fields that should take part in the comparison into another structure that you can embed in your original. When comparing, just compare the built-in fields:
type Person struct {
Name string
Age int
}
type Doc struct {
Person
Created time.Time
}
func main() {
d1 := Doc{
Person: Person{"Bob", 21},
Created: time.Now(),
}
time.Sleep(time.Millisecond)
d2 := Doc{
Person: Person{"Bob", 21},
Created: time.Now(),
}
fmt.Println(d1 == d2) // false
fmt.Println(d1.Person == d2.Person) // true
}
Try it on the go playground .
, , .., ==
. reflect.DeepEqual()
.
2.
, : , :
a := test{"testName", time.Now().Format(time.StampMilli)}
time.Sleep(time.Millisecond)
b := test{"testName", time.Now().Format(time.StampMilli)}
// Save and make excluded fields equal:
old := a.time
a.time = b.time
fmt.Println(a.name == b.name) // true
fmt.Println(reflect.DeepEqual(a, b)) // true
// Restore:
a.time = old
Go Playground.
, , , " ":
// Make copies and make excluded fields equal:
a2 := a
a2.time = b.time
fmt.Println(a2.name == b.name) // true
fmt.Println(reflect.DeepEqual(a2, b)) // true
Go Playground.
3.
, :
func compare(a, b test) bool {
return a.name == b.name
}
fmt.Println(a.name == b.name)
fmt.Println(compare(a, b))
Go Playground.
:
"", compare()
, , . ( Go Playground):
func compare(a, b test) bool {
a.time = b.time
return reflect.DeepEqual(a, b)
}
compare()
, , . ( Go Playground):
fmt.Println(a.name == b.name)
fmt.Println(compare(&a, &b))
func compare(a, b *test) bool {
a2 := new(test)
*a2 = *a
a2.time = b.time
return reflect.DeepEqual(a2, b)
}