1 回答
TA贡献1895条经验 获得超3个赞
要检查 a 是否time.Time
为零值,请使用Time.IsZero()
。
除此之外,只需一个接一个地实施您的规则。它不会是最有效的解决方案,但它会很干净和简单,一旦它正常工作,您就可以对其进行改进:
func isValid(slarti [][2]time.Time) bool {
now := time.Now()
for i, v := range slarti {
v1, v2 := v[0], v[1]
// Rule #3
if v1.IsZero() {
return false
}
// Rule #1: times must be in the past
if now.Before(v1) || now.Before(v2) {
return false
}
// Rule #2: times can't be the same
if v1.Equal(v2) {
return false
}
if i > 0 && v1.Equal(slarti[i-1][1]) {
return false
}
// Rule #3: invalid entry if no output before:
if i > 0 && slarti[i-1][1].IsZero() {
return false
}
// Rule #4: times must be in ascending order:
if !v2.IsZero() && v2.Before(v1) {
return false
}
if i > 0 && v1.Before(slarti[i-1][1]) {
return false
}
}
return true // Got this far: valid
}
这是测试所有规则以及有效输入的测试代码(在Go Playground上尝试):
cases := []struct {
name string
input [][2]time.Time
valid bool
}{
{
name: "Valid",
input: [][2]time.Time{{time.Date(2020, 11, 23, 8, 0, 0, 0, time.UTC), time.Date(2020, 11, 23, 9, 0, 0, 0, time.UTC)}},
valid: true,
},
{
name: "Valid (2)",
input: [][2]time.Time{{time.Date(2020, 11, 23, 8, 0, 0, 0, time.UTC), time.Date(2020, 11, 23, 9, 0, 0, 0, time.UTC)}, {time.Date(2020, 11, 23, 10, 0, 0, 0, time.UTC), time.Date(2020, 11, 23, 11, 0, 0, 0, time.UTC)}},
valid: true,
},
{
name: "Valid (3)",
input: [][2]time.Time{{time.Date(2020, 11, 23, 8, 0, 0, 0, time.UTC), time.Date(2020, 11, 23, 9, 0, 0, 0, time.UTC)}, {time.Date(2020, 11, 23, 10, 0, 0, 0, time.UTC), time.Time{}}},
valid: true,
},
{
name: "Rule #1",
input: [][2]time.Time{{time.Date(2023, 11, 23, 8, 0, 0, 0, time.UTC), time.Date(2023, 11, 23, 9, 0, 0, 0, time.UTC)}},
},
{
name: "Rule #2",
input: [][2]time.Time{{time.Date(2020, 11, 23, 8, 0, 0, 0, time.UTC), time.Date(2020, 11, 23, 8, 0, 0, 0, time.UTC)}},
},
{
name: "Rule #2 (2)",
input: [][2]time.Time{{time.Date(2020, 11, 23, 8, 0, 0, 0, time.UTC), time.Date(2020, 11, 23, 9, 0, 0, 0, time.UTC)}, {time.Date(2020, 11, 23, 9, 0, 0, 0, time.UTC), time.Date(2020, 11, 23, 11, 0, 0, 0, time.UTC)}},
},
{
name: "Rule #3",
input: [][2]time.Time{{time.Date(2020, 11, 23, 8, 0, 0, 0, time.UTC), time.Time{}}, {time.Date(2020, 11, 23, 10, 0, 0, 0, time.UTC), time.Date(2020, 11, 23, 11, 0, 0, 0, time.UTC)}},
},
{
name: "Rule #3 (2)",
input: [][2]time.Time{{time.Time{}, time.Date(2020, 11, 23, 9, 0, 0, 0, time.UTC)}, {time.Date(2020, 11, 23, 10, 0, 0, 0, time.UTC), time.Date(2020, 11, 23, 11, 0, 0, 0, time.UTC)}},
},
{
name: "Rule #4",
input: [][2]time.Time{{time.Date(2020, 11, 23, 8, 0, 0, 0, time.UTC), time.Date(2020, 11, 23, 7, 0, 0, 0, time.UTC)}, {time.Date(2020, 11, 23, 10, 0, 0, 0, time.UTC), time.Date(2020, 11, 23, 11, 0, 0, 0, time.UTC)}},
},
}
for i, c := range cases {
if valid := isValid(c.input); valid != c.valid {
log.Printf("[%d] %q expected valid: %t, got: %t", i, c.name, c.valid, valid)
}
}
- 1 回答
- 0 关注
- 100 浏览
添加回答
举报