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

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

问题描述

我希望对一个值进行建模,该值可以有两种可能的形式:不存在或字符串.

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

执行此操作的自然方法是使用 Maybe String、或 Optional、或 string option 等.但是,Go没有这样的变体类型.

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.

然后我想,继 Java、C 等之后,替代方案是可空性,或者 Go 中的 nil.但是,nil 不是 Go 中 string 类型的成员.

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.

搜索,然后我想到使用类型*string.这可以工作,但看起来很尴尬(例如,我不能像获取结构体地址那样获取字符串文字的地址).

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).

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

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

推荐答案

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

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
}

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

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

另一种可能是使用new:

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

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

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