如果你不能使用""
,返回一个类型的指针*string
;或者——因为这是 Go——你可以声明多个返回值,例如:(response string, ok bool)
.
Using *string
: 返回nil
当您没有“有用”字符串可返回时,可以使用指针。当您这样做时,将其分配给局部变量,并返回其地址。
func test() (response *string) {
if runtime.GOOS != "linux" {
return nil
} else {
ret := "useful"
return &ret
}
}
使用多个返回值:当您有一个有用的字符串要返回时,请使用以下命令返回它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
价值。否则,视为无用。
另请参阅相关问题:
如何在 Go 中表示可选字符串? https://stackoverflow.com/questions/30731687/how-do-i-represent-an-optional-string-in-go/30741287#30741287
获取和返回指针的替代方法string
: 如何在 Go 中执行文字 *int64 ? https://stackoverflow.com/questions/30716354/how-do-i-do-a-literal-int64-in-go/30716481#30716481