How to use variable package selector in go

huangapple go评论90阅读模式
英文:

How to use variable package selector in go

问题

我正在为你翻译以下内容:

我正在跟随 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] { // 这是我在 JavaScript 中的做法
	case today + 0:
		fmt.Println("Today.")
	default:
		fmt.Println("Too far away.")
	}
}

另外,我想知道我想要做的这个操作的正确术语是什么?我在使用谷歌搜索时没有找到太多有用的结果。

英文:

I'm following the Go tour, and still trying to learn the basics of the language. For the imported package time, is there a way to access its exports with a variable? E.g. time[day] instead of time.Saturday

Here's a more complete example

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.")
	}
}

Also, what is the correct terminology for what I want to do? I'm having very little luck using Google

答案1

得分: 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"])

参考 http://play.golang.org/p/6EYqcklf8X

英文:

No, there's no way to reference exported variables from a package, which are stored on the stack, without explicitly referencing them using a data structure that you define that's built at runtime.

For example, you could do:

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"])

See http://play.golang.org/p/6EYqcklf8X

huangapple
  • 本文由 发表于 2016年4月6日 13:38:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/36442415.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定