英文:
Does type definition help assign restricted values?
问题
在下面的结构体类型中:
type Employee struct {
Name string `json:"name"`
JobTitle JobTitleType `json:"jobtitle"`
}
成员JobTitle
应该确保具有受限制(特定)的字符串类型值。
type JobTitleType string
const(
GradeATitle JobTitleType = "Clerk"
GradeBTitle JobTitleType = "Manager"
)
类型定义(JobTitleType
)是否有助于为成员JobTitle
分配受限制的值?
英文:
In the below struct type:
type Employee struct {
Name string `json:"name"`
JobTitle JobTitleType `json:"jobtitle"`
}
member JobTitle
should be ensured to have restricted(specific) values( of string type).
type JobTitleType string
const(
GradeATitle JobTitleType = "Clerk"
GradeBTitle JobTitleType = "Manager"
)
Does type definition(JobTitleType
) help assign restricted values to member JobTitle
?
答案1
得分: 2
不。您可以为JobTitle分配任何值:
e.JobTitle = JobTitleType("bogus")
JobTitleType
基于字符串,因此所有字符串值都可以转换为它。
您可以使用getter/setters来强制运行时验证。
英文:
No. You can assign any value to JobTitle:
e.JobTitle=JobTitleType("bogus")
The JobTitleType
is based on string, so all string values can be converted to it.
You can use getter/setters to enforce runtime validation.
答案2
得分: 1
不,它不会限制值,任何具有类型JobTitleType
的值都可以分配给JobTitle。目前,Go语言中没有enum
类型。如果要限制值,你可能需要编写自己的逻辑。
英文:
No, it will not restrict the values, any value that has type JobTitleType
can be assigned to JobTitle. Currently, there is no enum
type in Go. For restricting values you will probably need to write your own logic.
答案3
得分: 1
不,你应该在验证逻辑中使用它。例如,https://github.com/go-playground/validator
提供了 oneOf
运算符用于验证。
Go语言没有 enum
类型,但你可以这样做:
package main
import (
"fmt"
)
var JobTitleTypes = newJobTitleTypeRegistry()
func newJobTitleTypeRegistry() *jobTitleTypeRegistry{
return &jobTitleTypeRegistry{
GradeATitle : "Clerk",
GradeBTitle : "Manager",
}
}
type jobTitleTypeRegistry struct {
GradeATitle string
GradeBTitle string
}
func main() {
fmt.Println(JobTitleTypes.GradeATitle)
}
英文:
No, you should use it in the validation logic. For example, https://github.com/go-playground/validator
has oneOf
operator for validation.
Go don't have enum
type, but you can do something like this
package main
import (
"fmt"
)
var JobTitleTypes = newJobTitleTypeRegistry()
func newJobTitleTypeRegistry() *jobTitleTypeRegistry{
return &jobTitleTypeRegistry{
GradeATitle : "Clerk",
GradeBTitle : "Manager",
}
}
type jobTitleTypeRegistrystruct {
GradeATitle string
GradeBTitle string
}
func main() {
fmt.Println(JobTitleTypes.GradeATitle)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论