在golang中,原始值的typedef是否等效?

鉴于此代码
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是否是有效且预定义的哲学常量.

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1 Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...