如何在Go中表示可选字符串? [英] How do I represent an Optional String in Go?

查看:151
本文介绍了如何在Go中表示可选字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望建立一个值,它可以有两种可能的形式:absent或者一个字符串。

自然的做法是使用 Maybe String 可选< String> 字符串选项等。 ,Go没有像这样的变体类型。

然后,我认为,遵循Java,C等,替代方法将是可空性,或 nil 。但是, nil 不是Go中字符串类型的成员。



搜索,然后我认为使用类型 * string 。这可能工作,但似乎很尴尬(例如,我不能以与我可以采取结构字面值的地址相同的方式取得字符串字面的地址)。

在Go中建立这样一个值的习惯用法是什么?

解决方案

您可以使用类似于 sql.NullString ,但我个人会坚持 *串。至于尴尬,不幸的是,你不能只是 sp:=&foo。但有一个解决方法

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

调用 strPtr(foo)应该内联,所以它实际上是&foo

另一种可能性是使用

  sp:= new(字符串)
* sp =foo


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"

这篇关于如何在Go中表示可选字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆