作者:伊子夕2010_593 | 来源:互联网 | 2023-06-29 12:04
正确处理方法:一、失败的原因只有一个时,不使用error例如:123456789func(self*AgentContext)CheckHostType(host_typestri
本文摘自php中文网,作者V,侵删。
![](https://img2.php1.cn/3cdc5/3909/cd5/cc486a404ad81923.jpeg)
正确处理方法:
一、失败的原因只有一个时,不使用error
例如:
1 2 3 4 5 6 7 8 9 | func (self *AgentContext) CheckHostType(host_type string) error {
switch host_type {
case "virtual_machine" :
return nil
case "bare_metal" :
return nil
}
return errors.New( "CheckHostType ERROR:" + host_type)
}
|
我们可以看出,该函数失败的原因只有一个,所以返回值的类型应该为bool,而不是error,重构一下代码:
1 2 | func (self *AgentContext) IsValidHostType(hostType string) bool {
return hostType == "virtual_machine" || hostType == "bare_metal" }
|
说明:大多数情况,导致失败的原因不止一种,尤其是对I/O操作而言,用户需要了解更多的错误信息,这时的返回值类型不再是简单的bool,而是error。
二、没有失败时,不使用error
error在Golang中是如此的流行,以至于很多人设计函数时不管三七二十一都使用error,即使没有一个失败原因。
我们看一下示例代码:
1 2 3 | func (self *CniParam) setTenantId() error {
self.TenantId = self.PodNs
return nil}
|
对于上面的函数设计,就会有下面的调用代码:
阅读剩余部分