问题描述
我有一个在某些情况下返回字符串的函数,即当程序在Linux或MacOS上运行时,否则返回值应为nil,以便在代码中进一步省略某些特定于OS的检查.
I have a function which returns a string under certain circumstances, namely when the program runs in Linux or MacOS, otherwise the return value should be nil in order to omit some OS-specific checks further in code.
func test() (response string) {
if runtime.GOOS != "linux" {
return nil
} else {
/* blablabla*/
}
}
但是,当我尝试编译此代码时,我得到一个错误:
however when I try to compile this code I get an error:
如果我只返回一个空字符串(如 return"
),则无法在代码中进一步将此返回值与 nil
进行比较.
If I return just an empty string like return ""
, I cannot compare this return value with nil
further in code.
所以问题是如何返回正确的nil字符串值?
So the question is how to return a correct nil string value?
谢谢.
推荐答案
如果不能使用"
,则返回类型为 * string
的指针;或-因为这是Go-您可以声明多个返回值,例如:(响应字符串,确定的布尔值)
.
If you can't use ""
, return a pointer of type *string
; or–since this is Go–you may declare multiple return values, such as: (response string, ok bool)
.
使用 * string
:当您没有要返回的有用"字符串时,返回 nil
指针.完成后,将其分配给局部变量,然后返回其地址.
Using *string
: return nil
pointer when you don't have a "useful" string to return. When you do, assign it to a local variable, and return its address.
func test() (response *string) {
if runtime.GOOS != "linux" {
return nil
} else {
ret := "useful"
return &ret
}
}
使用多个返回值:当您有有用的字符串要返回时,请以 ok = true
返回它,例如:
Using multiple return values: when you have a useful string to return, return it with ok = true
, e.g.:
return "useful", true
否则:
return "", false
它是这样的:
func test() (response string, ok bool) {
if runtime.GOOS != "linux" {
return "", false
} else {
return "useful", true
}
}
在调用方,首先检查 ok
返回值.如果这是 true
,则可以使用 string
值.否则,认为它没用.
At the caller, first check the ok
return value. If that's true
, you may use the string
value. Otherwise, consider it useless.
另请参阅相关问题:
获取和返回指向 string
的指针的替代方法:
Alternatives for obtaining and returning a pointer to string
: How do I do a literal *int64 in Go?
这篇关于如何在Go中返回Nil字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!