给定这段代码:
type Philosopher int
const (
Epictetus Philosopher = iota
Seneca
)
func Quote(who Philosopher) string {
fmt.Println("t: ", reflect.TypeOf(who))
switch who {
case Epictetus:
return "First say to yourself what you would be;
and do what you have to do"
case Seneca:
return "If a man knows not to which port he sails,
No wind is favorable"
}
return "nothing"
}
调用 Quote(5)
将打印 Foo.Philosopher
作为 5 的类型。
为什么类型检查器不提示,因为这是类型安全枚举应该做的,即限制值的范围?
最佳答案
这些不是您认为的枚举。 Philosopher
类型或多或少是 int 的别名。或多或少,因为它是一种根本不同的类型,可以定义自己的方法。
它的要点是以程序员清楚的方式提供常量的语义分组。此外,您还可以在编译期间受益于 Go 的类型检查器。但仅在传递给 func(Philosopher)
的值不能被隐式解释的情况下。将文字 5
作为参数传递是可行的,因为像 Go 中那样的常量本质上是无类型的。这行不通;
n := 5
Quote(n) // Compile error -> int is not Philosopher
原因是 n
被定义为 int
。 int
和 Philosopher
类型之间不存在隐式转换。但是,这会起作用:
n := 5
Quote(Philosopher(n))
因为类型转换是有效的。 Go 不关心 5
是否是一个有效的预定义的 Philosopher
常量。
关于go - golang 中原始值的 typedef 是否等效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22465501/