我有一个函数在某些情况下返回一个字符串,即当程序在Linux或MacOS中运行时,否则返回值应为nil,以便在代码中进一步省略某些特定于操作系统的检查.
func test() (response string) {
if runtime.GOOS != "linux" {
return nil
} else {
/* blablabla*/
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试编译此代码时,我收到一个错误:
test.go:10:3:不能在返回参数中使用nil作为类型字符串.
如果我只返回一个空字符串return "",我无法nil在代码中进一步比较此返回值.
那么问题是如何返回正确的nil字符串值?
谢谢.
icz*_*cza 19
如果你不能使用"",返回一个类型的指针*string; 或者 - 因为这是Go-你可以声明多个返回值,例如:(response string, ok bool).
使用*string:nil当没有"有用"字符串返回时返回指针.执行此操作时,将其分配给局部变量,并返回其地址.
func test() (response *string) {
if runtime.GOOS != "linux" {
return nil
} else {
ret := "useful"
return &ret
}
}
Run Code Online (Sandbox Code Playgroud)
使用多个返回值:当您有一个有用的字符串要返回时,返回它ok = true,例如:
return "useful", true
Run Code Online (Sandbox Code Playgroud)
除此以外:
return "", false
Run Code Online (Sandbox Code Playgroud)
这是它的样子:
func test() (response string, ok bool) {
if runtime.GOOS != "linux" {
return "", false
} else {
return "useful", true
}
}
Run Code Online (Sandbox Code Playgroud)
在调用者处,首先检查ok返回值.如果是这样true,您可以使用该string值.否则,认为它没用.
另见相关问题:
获取和返回指针的替代方法string:如何在Go中执行文字*int64?
这个特性在惯用的围棋中经常使用,例如从函数返回结果和错误值。
在你的情况下,它可能是这样的:
func test() (response string, err error) {
if runtime.GOOS != "linux" {
return "", nil
} else {
/* blablabla*/
}
}
Run Code Online (Sandbox Code Playgroud)
进而:
response, err := test()
if err != nil {
// Error handling code
return;
}
// Normal code
Run Code Online (Sandbox Code Playgroud)
如果您想忽略错误,只需使用_:
response, _ := test()
// Normal code
Run Code Online (Sandbox Code Playgroud)