-1

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?

overexchange
  • 15,768
  • 30
  • 152
  • 347
  • 1
    See related / possible duplicate: [Creating a Constant Type and Restricting the Type's Values](https://stackoverflow.com/questions/37385007/creating-a-constant-type-and-restricting-the-types-values/37386119?r=SearchResults#37386119) – icza Jun 14 '21 at 17:44

3 Answers3

2

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.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • One we have getter & setter, I need to make `JobTitle` as lowercase member(`jobTitle` ) to not assign the member directly, but, this will not allow to serialize data. How to enforce that the value is assigned only through setter? – overexchange Jun 14 '21 at 17:34
  • Keep it exported. There are no hard guarantees that the value will be valid. – Burak Serdar Jun 14 '21 at 17:36
  • Having member exported makes getter/setter redundant. – overexchange Jun 14 '21 at 17:42
1

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.

Rishabh Arya
  • 212
  • 5
  • 10
1

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)
}
Dmitrii Sidenko
  • 660
  • 6
  • 19