我正在关注Go之旅,并且仍在尝试学习该语言的基础知识。对于导入的包time
,有没有办法通过变量访问其导出?例如。 time[day]
代替time.Saturday
这是一个更完整的例子
package main
import (
"fmt"
"time"
)
func main() {
day := "Thursday"
fmt.Printf("When's %v?", day)
today := time.Now().Weekday()
switch time[day] { // This is how I would do it in javascript
case today + 0:
fmt.Println("Today.")
default:
fmt.Println("Too far away.")
}
}
另外,我想做什么的正确术语是什么?我使用谷歌的运气很少
答案 0 :(得分:2)
不,没有办法从包中引用导出的变量,这些变量存储在堆栈中,而不使用您定义的在运行时构建的数据结构显式引用它们。
例如,你可以这样做:
var days = map[string]time.Weekday{
"Monday": time.Monday,
"Tuesday": time.Tuesday,
"Wednesday": time.Wednesday,
"Thursday": time.Thursday,
"Friday": time.Friday,
"Saturday": time.Saturday,
"Sunday": time.Sunday,
}
fmt.Println(days["Thursday"])