小编arz*_*nus的帖子

如何限制 Golang 中变量的值?

我知道 Go 惯用语言没有 setter 和 getter。但我需要限制 Go 中变量的值。

我定义了新类型

type MyNewStringType string
Run Code Online (Sandbox Code Playgroud)

定义为 MyStringType 的变量需要限制值。

MyStringType 的变量只能有 3 个值:“是”、“否”、“我不知道”

我怎样才能在Golang中做到这一点?在Java、C++中我有setter和getter,但在Golang中并不正常。

我知道,我可以创造

type MyNewStringType struct {
   Variable string
}
Run Code Online (Sandbox Code Playgroud)

并创造

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")
  }
Run Code Online (Sandbox Code Playgroud)

但我认为这是错误的方式。

go

5
推荐指数
1
解决办法
5836
查看次数

标签 统计

go ×1