我试图表示一个简化的染色体,它由 N 个碱基组成,每个碱基只能是 {A, C, T, G}
之一。
我想用枚举形式化约束,但我想知道在 Go 中模拟枚举的最惯用的方法是什么。
原文由 carbocation 发布,翻译遵循 CC BY-SA 4.0 许可协议
我试图表示一个简化的染色体,它由 N 个碱基组成,每个碱基只能是 {A, C, T, G}
之一。
我想用枚举形式化约束,但我想知道在 Go 中模拟枚举的最惯用的方法是什么。
原文由 carbocation 发布,翻译遵循 CC BY-SA 4.0 许可协议
参考 jnml 的答案,您可以通过根本不导出 Base 类型(即写成小写)来防止 Base 类型的新实例。如果需要,您可以制作一个可导出接口,该接口具有返回基类型的方法。该接口可用于处理 Bases 的外部函数,即
package a
type base int
const (
A base = iota
C
T
G
)
type Baser interface {
Base() base
}
// every base must fulfill the Baser interface
func(b base) Base() base {
return b
}
func(b base) OtherMethod() {
}
package main
import "a"
// func from the outside that handles a.base via a.Baser
// since a.base is not exported, only exported bases that are created within package a may be used, like a.A, a.C, a.T. and a.G
func HandleBasers(b a.Baser) {
base := b.Base()
base.OtherMethod()
}
// func from the outside that returns a.A or a.C, depending of condition
func AorC(condition bool) a.Baser {
if condition {
return a.A
}
return a.C
}
在主包中 a.Baser
现在实际上就像一个枚举。只有在包内你可以定义新的实例。
原文由 metakeule 发布,翻译遵循 CC BY-SA 4.0 许可协议
7 回答5.3k 阅读
6 回答6.8k 阅读✓ 已解决
4 回答2.3k 阅读
1 回答3.3k 阅读
2 回答886 阅读✓ 已解决
2 回答2.2k 阅读
1 回答2.1k 阅读
引用语言规范: Iota
所以你的代码可能像
或者
如果您希望 bases 成为与 int 不同的类型。