duanba4942 2016-12-22 06:18
浏览 46
已采纳

数据结构只允许其中之一? Golang [重复]

This question already has an answer here:

What's a data structure that only allows one of a possible set of options?

I tried playing around with enums but they are not what I want.

package main

import "fmt"

type Event struct {
        day_number Day 
}

type Day int 

const (
        Monday Day = iota
        Tuesday
        Wednesday
        Thursday
        Friday
        Saturday
        Sunday
)

func main() {
        var r Event
        r.day_number = Monday
        fmt.Println(r.day_number)
        // Keep this from happening.
        var impossible Event
        impossible.day_number = 12
        fmt.Println(impossible.day_number)
}
</div>
  • 写回答

2条回答 默认 最新

  • douan3414 2016-12-22 06:43
    关注

    You could hide away the member field using a different package. This limits ways of creating the structure to functions from that package, and you can then control those functions to accept a limited set of inputs.

    foo/foo.go:

    package foo
    
    import "fmt"
    
    type entity int
    
    const (
        one entity = iota + 1
        two
    )
    
    type Foo struct {
        e entity
    }
    
    func (f Foo) Get() int {
        return int(f.e)
    }
    
    func NewFoo(i int) Foo {
        switch i {
        case 1:
            return Foo{one}
        case 2:
            return Foo{two}
        default:
            panic(fmt.Errorf("%s", "foo"))
        }
    }
    

    bar.go:

    package main
    
    import "fmt"
    import "./foo"
    
    func main() {
        f := foo.NewFoo(2)
        fmt.Println(f.Get())
        e := foo.Foo{3}  // Error: implicit assignment of unexported field 'e' in foo.Foo literal
        fmt.Println(e.Get())
        d := foo.NewFoo(3) // panic: foo!
        fmt.Println(d.Get())
    }
    

    You cannot create a Foo struct outside of the foo package, and the only function that creates Foo structs in a foo package accepts only a limited set of values.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)