duan111112 2019-08-19 09:55
浏览 35
已采纳

为什么const初始化器不能为nil? [重复]

This question already has an answer here:

I have a type A that is basically a simple map:

type A map[int32]struct{}

Now, I would like to have a special value of this type to be able to treat it a bit differently. I thought that it would be smart to use nil for this propose (additionally, this way, all non initialized variables of type A would have this value, and this is also what I would like to have):

const s A = nil

But I got

const initializer cannot be nil

Sure I can accept this and refactor my program in dozens of different ways. But I'm still wondering why it's impossible to initialize const to nil? There must be an architectural reason but I don't see it.

(Note that I prefer to "rename" nil instead of using it directly only because the name nil is not very intuitive in my case.)

</div>
  • 写回答

1条回答 默认 最新

  • doudong2149 2019-08-19 10:16
    关注

    I believe that it is because you can only have constants of type boolean, rune, integer, floating-point, complex, and string. Docs: https://golang.org/ref/spec#Constants

    Whereas nil is a zero-value for types pointer, interface, map, slice, channel and function Docs: https://golang.org/ref/spec#The_zero_value

    You can read more here https://blog.golang.org/constants

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码