dsomm80482 2015-06-09 12:10
浏览 94
已采纳

如何在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?

  • 写回答

2条回答 默认 最新

  • douzhouqin6223 2015-06-09 12:17
    关注

    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"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决