如何限制Golang中变量的值?

guys!

I know golang idiomatic don't have setter and getter. But I need to restrict value of variables in Golang.

I defined new type

type MyNewStringType string

And variables, that was defined as MyStringType, need to restrict value.

Variables of MyStringType can have only 3 values: "Yes", "No", "I don't know"

How can I do it in Golang? In Java, C++ I have setter and getter, but in Golang is not normal.

I know, I can create

type MyNewStringType struct {
   Variable string
}

and create

func(m *MyNewStringType) SetVariable(newVar string) error {
  if newVar == "Yes" || newVar == "No" || newVar == "I don't know" {
    m.Variable = newVar
    return nil
  } else {
    return errors.New("Wrong value")
  }

But I think it's wrong way.

Short awnser:

type MyString string
const (
    YES MyString = "yes"
    NO = "no"
    DONTKNOW = "i dont know"
)

func foo(arg MyString){
    fmt.Print(arg)
}

foo(YES) //success, prints "yes"

foo("jop") //fails to compile

A nicer way of implementing this could be to allow any value, and then validating when the value is used. A short example:

package main

import (
  "fmt"
  "os"
)

func main() {
  fmt.Println("First try")
  if err := doSomething("foo"); err != nil {
    fmt.Fprintf(os.Stderr, "%v
", err)
  }

  fmt.Println()

  fmt.Println("Second try")
  if err := doSomething("Yes"); err != nil {
    fmt.Fprintf(os.Stderr, "%v
", err)
  }
}

func doSomething(s string) error {
  switch s {
  case "Yes", "No", "I don't know":
    fmt.Println("Success!")
    return nil
  default:
    return fmt.Errorf("unsupported value: %q", s)
  }
}

Output:

First try
unsupported value: "foo"

Second try
Success!

https://play.golang.org/p/nt8J9wdlZkp

If you insist on implementing it in the way you suggest, perhaps your SetVariable method would become a little bit tidier if you used a switch statement as in the above example.