错误处理,是非常重要的。在go语言中,错误处理被设计的十分简单。
如果做得好,会在排查问题等方面很有帮助;如果做得不好,就会比较麻烦。
从1.0开始,go中定义错误为 error 接口
// The error built-in interface type is the conventional interface for // representing an error condition, with the nil value representing no error. type error interface { Error() string }
go语言中,错误处理的几种方式:
立即学习“go语言免费学习笔记(深入)”;
1、通过判断值相等。像 io.EOF,go语言中,称为 sentinel error
2、通过断言( type assertion or type switch),判断err的类型或者是否实现了某个接口
3、利用包提供的方法。像 os.IsNotExist。go语言中,称为 ad-hoc check
4、当上面3中方式不可用时,通过搜索 err.Error() 是否包含特定字符串。(不被推荐)
尽量不要使用 sentinel error
尽量不要使用 ad-hoc check
以上就是golang中的错误处理方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号