How do I represent an Optional String in Go?

后端 未结 2 1374
盖世英雄少女心
盖世英雄少女心 2020-12-04 01:30

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

2条回答
  •  隐瞒了意图╮
    2020-12-04 02:07

    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"
    

提交回复
热议问题