类型定义有助于分配受限制的值吗?

huangapple go评论79阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2021年6月15日 01:27:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/67974698.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定