英文:
Returning multiple values from function
问题
我有这个函数:
func GetBasicAuth(w http.ResponseWriter, r *http.Request) (string, error) {
secret, _, ok := r.BasicAuth()
if !ok {
return "", err //这样写对吗?
}
return secret, nil
}
我不得不声明这个函数将返回一个字符串和一个错误,但实际上它将返回其中之一。如果BasicAuth函数的ok
值为false,那么我没有字符串可以返回,那么在这种情况下我该怎么办 - 只是返回一个空字符串吗?这看起来很奇怪!
英文:
I have this function:
func GetBasicAuth(w http.ResponseWriter, r *http.Request) (string, error) {
secret, _, ok := r.BasicAuth()
if !ok {
return "", err //is this right?
}
return secret, nil
}
I've had to declare that the function will return a string and an error but in reality it will return one or the other. If the BasicAuth function wasn't ok
then I have no string to return so what do I do here - just send an empty string? This seems weird!
答案1
得分: 2
除非另有说明(例如io.Reader
),在Go语言中,返回a, b, c, …, error
的函数/方法通常会期望如果err != nil
,则所有其他返回值都是未定义的,不应使用或检查。通常(但不是必须的),当返回错误时,函数/方法会使用那些其他返回值的零值。
正如前面提到的,一些函数/方法(例如io.Reader
的Read(p []byte) (n int, err error)
)明确说明了其他行为:
在考虑错误
err
之前,调用者应始终处理返回的n > 0个字节。
而且,你创建的任何返回有用值的函数/方法,即使在某些错误情况下,也应该明确说明。
英文:
Unless documented otherwise (e.g. io.Reader
),
it's normal for Go functions/methods returning a, b, c, …, error
to expect that if err != nil
that all other returned values are undefined and should not be used/examined.
It's usual (but not required) that when returning an error
the function/method uses whatever the zero value is for those other return values.
As mentioned, some functions/methods such as an io.Reader
's Read(p []byte) (n int, err error)
explicitly state other behaviour:
>Callers should always process the n > 0 bytes returned before
considering the error err.
And any functions/methods you create that return useful values even in the case of (some) errors should probably explicitly state that.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论