为何这个类型不能声明为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)
阅读 3k
3 个回答

应该传值 ,传指针是不不行的

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())
}

感觉你这个comma,ok语句没写对。

if _, ok := v.(int); ok {
    fmt.Printf("%d\n", v)
}
新手上路,请多包涵

不明白为什么要做这个操作。判断不是nil,直接print就好了啊

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题