duanpuchen3142 2018-10-01 11:11
浏览 59

在golang中定义为常数的结构的受限值时,如何降低冗长性?

Suppose I have the following snippet in my package:

package fruits

type fruitType uint8

const(
    banana fruitType = iota
    apple fruitType = iota
    strawberry fruitType = iota
)

type allFruitTypes struct {
       Banana fruitType
       Apple fruitType
       Strawberry fruitType
}

var allFruitTypesImpl = allFruitTypes {
    Banana: banana,
    Apple: apple,
    Strawberry: strawberry,
}

//GetAllFruitTypes returns a list with all the possible fruit types
func GetAllFruitTypes() *allFruitTypes {
 return &allFruitTypesImpl 
}

In this way, I can avoid that outside my package new types of fruits are created. And still it allows to read my list of possible fruit types. Is that correct?

So my main problem in here is that I find really annoying to define 3 things that mean the same:

  1. the consts using iota
  2. the declaration of the struct type
  3. defining the struct implementation and typing in the values for each member.

For me, semantically the three of them mean the same. However, because of the way go works (or my lack of knowledge on how to type this better in go) I have to retype the same thing 3 times.

Is there any way to cause the same effect without having to type down the very same semantics 3 times?

  • 写回答

1条回答 默认 最新

  • douhui5953 2018-10-01 11:49
    关注

    This is the shortest:

    //FruitTypes has a field for every fruit type
    type FruitTypes struct {
        Banana, Apple, Strawberry uint8
    }
    
    //Fruits returns a list with all the possible fruit types
    func Fruits() *FruitTypes {
        return &FruitTypes{0, 1, 2}
    }
    

    If you need constants

    const (
        banana uint8 = iota
        apple
        strawberry
    )
    
    //FruitTypes has a field for every fruit type
    type FruitTypes struct {
        Banana, Apple, Strawberry uint8
    }
    
    //Fruits returns a list with all the possible fruit types
    func Fruits() *FruitTypes {
        return &FruitTypes{banana, apple, strawberry}
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频