如何在Golang中返回错误?
In Golang, we return errors explicitly using the return statement. This contrasts with the exceptions used in languages like java, python. The approach in Golang to makes it easy to see which function returns an error?
在Golang中,我們使用return語句顯式返回錯誤。 這與Java,Python等語言中使用的例外形成對比。 Golang中的方法可以輕松查看哪個函數(shù)返回錯誤 ?
In Golang, errors are the last return value and have type error, a built-in interface.
在Golang中,錯誤是最后一個返回值,其錯誤類型為內(nèi)置接口。
errors.New() is used to construct basic error value with the given error messages.
errors.New()用于根據(jù)給定的錯誤消息構造基本錯誤值。
We can also define custom error messages using the Error() method in Golang.
我們還可以使用Golang中的Error()方法定義自定義錯誤消息 。
How to create an error message in Golang?
如何在Golang中創(chuàng)建錯誤消息?
Syntax:
句法:
err_1 := errors.New("Error message_1: ")err_2 := errors.New("Error message_2: ")Basic program to test an error in Golang
測試Golang錯誤的基本程序
package mainimport ("fmt""errors")func test(value int) (int, error) {if (value == 0) {return 0, nil;} else {return -1, errors.New("Invalid value: ")} }func main() {value, error := test(10)fmt.Printf("Value: %d, Error: %v", value, error)value, error = test(0)fmt.Printf("\n\nValue: %d, Error: %v", value, error) }Output
輸出量
Value: -1, Error: Invalid value: Value: 0, Error: <nil>翻譯自: https://www.includehelp.com/golang/how-to-return-an-error-in-golang.aspx
總結
以上是生活随笔為你收集整理的如何在Golang中返回错误?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 种植牙大概多少钱一颗啊?
- 下一篇: ruby 嵌套函数_Ruby嵌套直到循环