我在 Go 中有一个结构,如下所示:
type A struct {
Name string
Type string
Time string
}
我想写一个
less
函数来比较两个struct A,比如
func (s A) less(other A) bool {
if s.Name < other.Name {
return True
}
if other.Name < s.Name {
return False
}
if s.Type < other.Type {
return True
}
if other.Type < s.Type {
return False
}
return s.Time < other.Time
}
我想知道是否有更好的方法/更简单的方法来编写这个逻辑?谢谢!
这是一种更简短的写法:
func (s A) Less(other A) bool {
switch {
case s.Name != other.Name:
return s.Name < other.Name
case s.Type != other.Type:
return s.Type < other.Type
default:
return s.Time < other.Time
}
}