我有一个Go应用程序,它需要无限数量的常量集。应用程序还要求我能够在运行时将字符串映射到(整数) consts,反之亦然。常量的名称只保证是有效的标识符,因此几乎肯定会有重复的const名称。特别是,每一组常量都有一个名为“无效”的元素。在C++11中,我会使用枚举类来实现范围。在Python中,我可能会使用类变量。我很难找到一种惯用的方式来表达这一点。我看过的选项包括:
first.go
package first
type First int
const (
ConstOne First = iota
ConstTwo
Invalid = -1
)
func IntToCode(fi First)string { ... }
func CodeToInt(code string)First { ... }second.go
package second
type Second int
const (
ConstOne Second = iota
ConstTwo
Invalid = -1
)
func IntToCode(se Second)string { ... }
func CodeToInt(code string)Second { ... }example.go
import (
"first"
"second"
)
First fi = first.CodeToInt("ConstOne")
Second se = second.Invalidfirst.go
package mypackage
type First int
const (
FI_CONSTONE First = iota
FI_CONSTTWO
FI_INVALID = -1
)
func IntToCode(fi First)string { ... }
func CodeToInt(code string)First { ... }second.go
package mypackage
type Second int
const (
SE_CONSTONE Second = iota
SE_CONSTTWO
SE_INVALID = -1
)
func IntToCode(se Second)string { ... }
func CodeToInt(code string)Second { ... }example.go
package mypackage
import (
"first"
"second"
)
First fi = first.CodeToInt("ConstOne")
Second se = SE_INVALID更好更地道的解决方案是什么?我希望能说出这样的话:
First fi = First.Invalid但我并没有成功地想出一种允许这样做的方法。
发布于 2015-12-30 02:07:31
您可以为单独的代码集拥有单独的包,也可以有一个单独的包来定义与代码关联的更高级别的功能,并为该更高级别的包编写测试。
我没有编译或测试这些:
例如,用于一组代码:
package product // or whatever namespace is associated with the codeset
type Const int
const (
ONE Const = iota
TWO
...
INVALID = -1
)
func (c Const) Code() string {
return intToCode(int(c)) // internal implementation
}
type Code string
const (
STR_ONE Code = "ONE"
...
)
func (c Code) Const() int {
return codeToInt(string(c)) // internal implementation
}例如,对于较高级别的函数包:
// codes.go
package codes
type Coder interface{
Code() string
}
type Conster interface{
Const() int
}
func DoSomething(c Coder) string {
return "The code is: " + c.Code()
}
// codes_product_test.go
package codes
import "product"
func TestProductCodes(t *testing.T) {
got := DoSomething(product.ONE) // you can pass a product.Const as a Coder
want := "The code is: ONE"
if got != want {
t.Error("got:", got, "want:", want)
}
}编辑:
要检索特定代码的const,可以执行以下操作
product.Code("STRCODE").Const()如果Const()返回一个Coder,这样product.Code("ONE").Const()就可以成为一个product.Const,也许会更好。我认为如果你在这里玩的话,有几个选择,在那里会有一个很好的选择。
https://stackoverflow.com/questions/34502647
复制相似问题