How do I represent an Optional String in Go?


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?


You could use something like sql.NullString, but I personally would stick to *string. As for awkwardness, it’s true that you can’t just sp := &"foo" unfortunately. But there is a workaround for this:

func strPtr(s string) *string {
    return &s

Calls to strPtr("foo") should be inlined, so it’s effectively &"foo".

Another possibility is to use new:

sp := new(string)
*sp = "foo"

Answered By – Ainar-G

Answer Checked By – Marie Seifert (GoLangFix Admin)

Leave a Reply

Your email address will not be published.