在Go中创建具有约束的自定义类型 [英] Create a custom type with constraint in Go
问题描述
如何在Go中创建只能接受有效值的自定义类型?例如,我要创建一个名为名称"的类型,其基础类型为字符串.但是,它只能接受值"John","Rob"或"Paul".其他任何值都将返回错误.我已经以一种非常简单的方式创建了以下程序,以表示我想要实现的目标.
How do I create a custom type in Go where only valid values can be accepted? For example, I want to create a type called "Names" where its underlying type is a string. However it can only accept the values "John", "Rob" or "Paul". Any other value will return an error. I've create the following program in a very simplistic way just to represent what I would like to achieve.
http://play.golang.org/p/jzZwALsiXz
编写此代码的最佳方法是什么?
What would be the best way to write this code?
推荐答案
您可以执行以下操作(http://play.golang.org/p/JaIr_0a5_- ):
You could do something like this (http://play.golang.org/p/JaIr_0a5_-):
type Name struct {
string
}
func (n *Name) String() string {
return n.string
}
func NewName(name string) (*Name, error) {
switch name {
case "John":
case "Paul":
case "Rob":
default:
return nil, fmt.Errorf("Wrong value")
}
return &Name{string: name}, nil
}
Golang不提供运算符重载,因此您无法在强制转换或影响值时进行检查.
Golang does not provide operator overload so you can't make the check while casting or affecting value.
根据您要尝试执行的操作,您可能需要执行以下操作( http://play.golang.org/p/uXtnHKNRxk ):
Depending on what you are trying to do, you might want to do something like this (http://play.golang.org/p/uXtnHKNRxk):
type Name string
func (n Name) String() string {
switch n {
case "John":
case "Paul":
case "Rob":
default:
return "Error: Wrong value"
}
return string(n)
}
这篇关于在Go中创建具有约束的自定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!