Golang tour切换评估顺序:time.Now()。Weekday()+ 2产生运行时错误:索引超出范围

时间:2017-06-02 08:58:43

标签: go time

我正在学习Golang,正在浏览我找到关于切换评估顺序的教程。我修改了一下(例如周六到周日),只是为了玩。它打印太远了。即使是星期天。所以,我修改了代码看起来像这样:

package main

import (
    "fmt"
    "time"
)

func main() {
    day := time.Monday

    fmt.Printf("When's %v?\n", day)
    today := time.Now().Weekday()

    switch day {
    case today + 0:
        fmt.Println("Today.")
    case today + 1:
        fmt.Println("Tomorrow.", today + 1)
    case today + 2:
        fmt.Println("In two days.", today + 2)
    default:
        fmt.Println("Too far away.", today + 2)
    }
}

现在,它给了我输出:

When's Monday?
Too far away. %!v(PANIC=runtime error: index out of range)

我可以对MOD进行哪些操作,而不是将其添加到数组之外?对我来说就像某种运算符重载一样。在添加操作时,它不应该是MOD,默认情况下是天,至少是?

1 个答案:

答案 0 :(得分:4)

这是一个实施细节。

在这一行

fmt.Println("In two days.", today + 2)

today属于time.Weekday类型,其基础类型为int2为无类型整数常量,将转换为time.Weekday并且增加将进行。

fmt.Println()的实现会检查传递给它的值是否实现fmt.Stringer,并且因为time.Weekday会这样做,所以将调用其String()方法,其实现方式为:

// String returns the English name of the day ("Sunday", "Monday", ...).
func (d Weekday) String() string { return days[d] }

其中days是包含7个元素的数组:

var days = [...]string{
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
  }

Weekday.String()中没有范围检查,因为例如time.Saturday + 2不是工作日。 Weekday.String()仅保证对time包中定义的常量正常工作:

type Weekday int

const (
    Sunday Weekday = iota
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday
)

如果你想让它起作用,你必须在除以7之后使用余数,如下所示:

switch day {
case (today + 0) % 7:
    fmt.Println("Today.")
case (today + 1) % 7:
    fmt.Println("Tomorrow.", (today+1)%7)
case (today + 2) % 7:
    fmt.Println("In two days.", (today+2)%7)
default:
    fmt.Println("Too far away.", (today+2)%7)
}