当前位置:网站首页>GO语言-自定义error
GO语言-自定义error
2022-06-23 03:56:00 【一边学习一边哭】
目录
前言
error是go语言中的一种数据类型,内置接口。定义了一个方法Error() string
error接口

error接口的实现--errorString结构体,实现Error方法。

内置包创建错误对象
go语言内置的errors包下的New()函数和fmt包下的Errorf(),都可以创建一个error对象。
func main() {
err1 := errors.New("通过errors.New()创建的错误")
fmt.Printf("err1:%v, 类型:%T\n", err1, err1)
err2 := fmt.Errorf("通过fmt.Errorf()创建的错误")
fmt.Printf("err2:%v, 类型:%T\n", err2, err2)
}
自定义error接口的实现
从前言中可以看出来,error接口十分简单。要实现error接口,只需要自定义一个结构体,实现Error()方法即可。
下面我们就自定义实现一下errror接口。函数输入年龄的值进行判断,过大过小都进行报错。
type AgeError struct {
msg string
age int
}
func (a *AgeError) Error() string {
return a.msg + ", 年龄是:" + strconv.Itoa(a.age)
}
func main() {
age, err := ageVerification(200)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(age)
}
}
func ageVerification(age int) (int, error) {
if age > 150 || age < 0 {
return age, &AgeError{"年龄不合法", age}
}
return age, nil
}![]()
边栏推荐
- MCS: discrete random variable
- Snippet Manager snippetslab
- Baidu PaddlePaddle's "universal gravitation" first stop in 2022 landed in Suzhou, comprehensively launching the SME empowerment plan
- markdown给图片加背景色
- A bug in rtklib2.4.3 B34 single point positioning
- Raspberry pie network remote access
- TIOBE 编程语言排行榜是编程语言流行趋势的一个指标
- MySQL自定义序列数的实现
- Beyond chips and AI, why is hard technology capital becoming more and more "hard core"?
- Error related to synchronizing domestic AOSP code
猜你喜欢
随机推荐
弱者易怒如虎,强者平静如水,真正厉害的人早已戒掉了情绪
How to conduct exploratory data analysis
99 multiplication table bat
[microservices | Nacos] Nacos realizes data isolation of multi environment and multi tenant
How can functional testers spend one month to become advanced automation software test engineers
JVM原理之内存模型
Event log keyword: eventlogtags logtags
Economic development is driven by new technology
Rtklib new version 2.4.3 B34 test comparison
UI automation positioning edge -xpath actual combat
(IntelliJ)插件一 Background Image Plus
C语言栈实现
同步国内AOSP代码相关错误
Jenkins安装部署以及自动构建和发布jar应用
Drama asking Huamen restaurant Weng
Mysql入门学习(一)之语法
MCS: continuous random variable lognormal distribution
Fund performance evaluation
大環境不好難找工作?三面阿裏,幸好做足了准備,已拿offer
Missing essential plugin









