在定义golang中倾向于常量的结构的限制值时,如何减少冗长?
假设我的包中有以下代码段:在定义golang中倾向于常量的结构的限制值时,如何减少冗长?,go,struct,scope,Go,Struct,Scope,假设我的包中有以下代码段: package fruits type fruitType uint8 const( banana fruitType = iota apple fruitType = iota strawberry fruitType = iota ) type allFruitTypes struct { Banana fruitType Apple fruitType Strawberry fruitTyp
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
}
通过这种方式,我可以避免在我的包装之外产生新类型的水果。尽管如此,它仍然可以阅读我列出的可能的水果种类。对吗
所以我这里的主要问题是,我发现定义三个意思相同的东西真的很烦人:
//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}
}
如果你需要常数
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}
}
您的一些问题已在此处解决:。此外,如果您的类型未导出,则无法创建新类型的水果并将其注册到原始包中。Hej,谢谢。这段代码当然更短。但是,它还需要对每件事声明3次。我想知道你是否可以一次申报,或者只申报两次。@Jose你需要申报吗?常量列表不够吗?因为如果我们只定义常量,可以说篮球水果类型=48,但首先,篮球是一项运动,而不是水果。第二,我没有一个剥篮球的实现,只知道如何剥我清单上的果实