有没有更简单的方法在 Go 中编写这个逻辑?

问题描述 投票:0回答:1

我在 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
}

我想知道是否有更好的方法/更简单的方法来编写这个逻辑?谢谢!

go struct compare logic comparator
1个回答
0
投票

这是一种更简短的写法:

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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.