什么是返回可选值和可能错误的函数的最佳签名?
例如:
func findColor(name string) (RGB, error) {
...
}
(空RGB值为黑色,是有效颜色,因此您无法使用它来推断未找到任何值。假设错误可能来自类似数据库的连接。)
看起来最好的两个选项是布尔返回值:
func findColor(name string) (RGB, bool, error) {
...
}
c, ok, err := findColor(myname)
if !ok {
...
} else if err != nil {
...
}
...
或特殊错误值:
var ColorNotFound = errors.New(...)
func findColor(name string) (RGB, error) {
...
}
c, err := findColor(...)
if err == ColorNotFound {
...
} else if err != nil {
...
}
...
(制造特殊错误似乎很痛苦。)
最常用的方法是什么?
答案 0 :(得分:6)
Go中的约定是返回(value, error)
,如果error != nil
则value
是(或可能)无效。
如果您有特殊错误,则需要执行某些操作(例如io.EOF),然后发出特定错误是正常做法。所以如果你想为ColorNotFound
做一些不同的事情,我会说你的第三个例子是最惯用的。
var ColorNotFound = errors.New(...)
func findColor(name string) (RGB, error) {
// ...
}
c, err := findColor(...)
if err == ColorNotFound {
// Do something special if ColorNotFound...
} else if err != nil {
// Some other kind of error...
}
答案 1 :(得分:1)
您可以findColor
返回*RGB
,然后将其与nil进行比较:
c, err := findColor(name)
if err != nil { /* Handle error. */ }
if c == nil { /* Handle no color. */ }
这是不安全的,因为如果你试图在nil
指针上调用方法,它们会引起恐慌。
我建议坚持使用特殊的ErrColorNotFound
方法。