duanhuang2150 2017-06-05 18:44
浏览 65

缺少对数组常量的支持的解决方法? [重复]

This question already has an answer here:

Go doesn't have array constants.

My application receives messages containing several types of numeric codes which I need to display as phrases.

If array contants existed I could do something like:

func foo() {
   ...
   fmt.Println(facename[f])
   ...
}
const facename [...]string = "top", "bottom", "left", "right", "front", "back"

But of course there's no way to do this. The first way around this that occurs to me, and maybe a reasonable efficient one is to use a switch

func foo() {
   ...
   name := "unknown"
   switch f {
   case 0:
      name = "top"
   case 1:
      name = "bottom"
   case 2:
      name = "left"
   case 3:
      name = "right"
   case 4:
      name = "front"
   case 5:
      name = "back"
   }
   fmt.Println(name)
   ...
}

The above is rather tedious if the number of values gets to be twenty or more.

It seems the most concise way is something like

func foo() {
   ...
   fmt.Println(strings.Split(facenames,",")[f])
   ...
}
const facenames = "top,bottom,left,right,front,back"

I will also have to check that the index is in range of course. Although efficiency isn't a concern at the moment, it bugs me that I'm using strings.Split() more than I want to.

Is there another way that is either idiomatic or both concise and efficient?

</div>
  • 写回答

2条回答 默认 最新

  • doulian8742 2017-06-05 19:14
    关注

    The idiomatic approach is to use a package level variable:

    var facename = []string{"top", "bottom", "left", "right", "front", "back"}
    
    func foo() {
        // ...
        fmt.Println(facename[f])
        // ...
    }
    

    It's also idiomatic to use a slice instead of an array in this situation.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题