dsomm80482
dsomm80482
2015-06-09 12:10

如何在Go中表示可选字符串?

  • string
  • null
  • variant

I wish to model a value which can have two possible forms: absent, or a string.

The natural way to do this is with Maybe String, or Optional<String>, or string option, etc. However, Go does not have variant types like this.

I then thought, following Java, C, etc., that the alternative would be nullability, or nil in Go. However, nil is not a member of the string type in Go.

Searching, I then thought to use the type *string. This could work, but seems very awkward (e.g. I cannot take the address of the string literal in the same way that I can take the address of a struct literal).

What is the idiomatic way to model such a value in Go?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答