在golang中,原始值的typedef是否等效?
发布时间:2020-12-16 19:26:44 所属栏目:大数据 来源:网络整理
导读:鉴于此代码: type Philosopher intconst ( 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 w
鉴于此代码:
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是否是有效且预定义的哲学常量. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |