鉴于此代码:
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"
}
Run Code Online (Sandbox Code Playgroud)
调用Quote(5)将打印Foo.Philosopher为类型5.为什么类型检查器没有抱怨,因为类型安全枚举应该做什么,即限制值的范围?
这些都不是你想到的枚举.Type Philosopher或多或少是int的别名.或多或少,因为它是一个基本上不同的类型,可以定义自己的方法.
它的关键是以程序员清楚的方式提供常量的语义分组.另外,在编译期间可以获得Go的类型检查器的好处.但只有在传递给a的值func(Philosopher)不能被隐含地解释为这样的程度.传递文字5作为参数有效,因为Go中的常量本身就是无类型的.这不起作用;
n := 5
Quote(n) // Compile error -> int is not Philosopher
Run Code Online (Sandbox Code Playgroud)
理由是n被定义为int.类型int和之间不存在隐式转换Philosopher.但是,这将有效:
n := 5
Quote(Philosopher(n))
Run Code Online (Sandbox Code Playgroud)
因为类型转换是有效的.Go不关心是否5是有效且预定义的Philosopher常量.
| 归档时间: |
|
| 查看次数: |
12219 次 |
| 最近记录: |