golang - 为何这个类型不能声明为error类型
本文介绍了golang - 为何这个类型不能声明为error类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
package main
import "fmt"
type Test struct {
a string
}
func (t *Test)Error() string{
return t.a
}
func main() {
test1 := new(Test)
test1.a = "oops"
p := *test1
hasError(p)
}
func hasError (e error){
fmt.Printf("%s",e.Error())
}
我想要 把这个类型声明为error类型的时候就会出错
cannot use *test1 (type Test) as type error in argument to hasError:
Test does not implement error (Error method has pointer receiver)
解决方案
应该传值 ,传指针是不不行的
package main
import "fmt"
type Test struct {
a string
}
func (t *Test)Error() string{
return t.a
}
func main() {
test1 := new(Test)
test1.a = "oops"
p := *test1
////
hasError(&p)
}
func hasError (e error){
fmt.Printf("%s",e.Error())
}
这篇关于golang - 为何这个类型不能声明为error类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文