英文:
Return if there is no error Golang
问题
在Golang中,运行以下函数是否可以:
err, value := function()
if err == nil {
return value
}
而不是这样做:
err, value := function()
if err != nil {
panic(err)
}
return err
如果可以的话,是否有时间上的优势/奖励?
这不是一个非致命错误。我正在尝试将某些内容转换为不同的类型,但我不确定应该使用哪种方式。
英文:
In Golang, is it ok to run the function
err, value := function()
if err == nil {
return value
}
instead of doing this:
err, value := function()
if err != nil {
panic(err)
}
return err
If so, is there any time advantages / bonuses?
This is not a non-fatal error. I am trying to convert something to different types, and i'm not sure which I should use.
答案1
得分: 6
恐慌(panic)类似于异常,但不会传递给调用者(也就是说,当你调用恐慌时,它会立即发生;你不能等待)。你应该使用代码的第一个示例,在那里你可以尝试一个动作,失败,然后继续执行。
func main() {
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
// 生成一些随机数,并调用add()函数
for i := 0; i < 10; i++ {
s, err := add(r1.Intn(100), r1.Intn(100))
if err != nil {
fmt.Println(err)
continue
}
fmt.Println(s)
}
}
// 如果和超过100,则返回错误
func add(a int, b int) (int, error) {
s := a + b
if s > 100 {
return s, errors.New("嘿,笨蛋,出错了!")
}
return s, nil
}
如果在这个示例中发生恐慌,程序将会终止(试试吧——不要返回错误,而是使用panic("Some error")
)。但是,我们决定出现错误时,可以尝试生成另一个随机数。
正如其他人所说,如果你有一个情况,你根本无法恢复(比如你试图从一个文件中读取数据,但文件不存在),你可能会决定使用恐慌更好。但是,如果你有一个长时间运行的进程(比如一个API),你可能希望继续运行,而不管任何错误。
GoPlay链接:http://play.golang.org/p/ThXTxVfM6R
原帖更新了一个用例——他试图将一个类型转换。如果你在这个函数中发生恐慌,你将无法继续执行。相反,我们希望返回一个错误,让调用者决定如何处理这个错误。以下是一个示例:
func interfaceToString(i interface{}) (string, error) {
if i == nil {
return "", errors.New("nil interface")
}
switch i.(type) {
case string:
return i.(string), nil
case float64:
return strconv.Itoa(int(i.(float64))), nil
case int:
return strconv.Itoa(i.(int)), nil
}
return "", errors.New(fmt.Sprintf("无法转换 %v", i))
}
GoPlay链接:http://play.golang.org/p/7y7v151EH4
英文:
A panic is similar to an exception, but doesn't get passed to the caller (aka when you call panic, it happens then and there; you don't get to wait). You should go with the first sample of your code, where you can attempt an action, fail, and continue.
func main() {
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
// Generate some random numbers, and call into add()
for i := 0; i < 10; i++ {
s, err := add(r1.Intn(100), r1.Intn(100))
if err != nil {
fmt.Println(err)
continue
}
fmt.Println(s)
}
}
// Error if we get a sum over 100
func add(a int, b int) (int, error) {
s := a + b
if s > 100 {
return s, errors.New("Hey doofus, error!")
}
return s, nil
}
If you were to panic in this example, you'd be done (try it-- instead of returning an error do panic("Some error"). But instead, we determine there's an error, and we can try to generate another random number.
Like others have said, if you have a use case where you just can't recover (say you were trying to read from a file, but the file isn't there), you might decide it's better to panic. But if you have a long running process (like an API), you'll want to keep churning, despite any errors.
GoPlay here: http://play.golang.org/p/ThXTxVfM6R
OP has update his post with a use case-- he's trying to convert to a type. If you were to panic in this function, you would be dead in the water. Instead, we want to return an error, and let the caller decide what to do with the error. Take this as an example:
func interfaceToString(i interface{}) (string, error) {
if i == nil {
return "", errors.New("nil interface")
}
switch i.(type) {
case string:
return i.(string), nil
case float64:
return strconv.Itoa(int(i.(float64))), nil
case int:
return strconv.Itoa(i.(int)), nil
}
return "", errors.New(fmt.Sprintf("Unable to convert %v", i))
}
GoPlay here: http://play.golang.org/p/7y7v151EH4
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论