首页 文章

如何将接口传递给具有大量参数的方法

提问于
浏览
-1

我编写了一个惰性代码来演示我必须实现接口的问题 . 我有方法M1,M2,它将struct X作为参数并且具有struct Y的类型 . 我希望所有这些方法都由单个接口I实现 . 问题是实现我需要知道的接口的方法M需要传递给子方法的参数(M1,M2) . 我收到错误: <argument name> used as a value 当我在M中传递多个参数时

type Y struct {
 a int
}

type X struct {
 a int
}

(y *Y) func M1(x X) struct {
 return y.a+x.a
}

(y *Y) func M2(x X) struct {
 return y.a*x.a
}

type I interface {
 M1(x X)
 M2(x X)
}

func M(i I, x X) {
 fmt.println(i.M1(x)) //returns an error i.M1(x) used as a value
 fmt.println(i.M2(x)) //returns an error i.M2(x) used as a value
}

1 回答

  • 3

    在您的示例中导致 <argument name> used as a value 错误的问题是,表示接口 I 的函数被声明为没有返回值:

    type I interface {
     M1(x X)
     M2(x X)
    }
    

    当然,如果函数不返回任何内容,则无法将函数调用作为 Println 的参数传递: fmt.println(i.M1(x)) . 更改示例中的接口声明以返回一些内容(以及一些其他修复*):

    type Y struct {
     a int
    }
    
    type X struct {
     a int
    }
    
    func(y *Y) M1(x X) int {
     return y.a+x.a
    }
    
    func(y *Y) M2(x X) int {
     return y.a*x.a
    }
    
    type I interface {
     M1(x X) int
     M2(x X) int
    }
    
    func M(i I, x X) {
     fmt.Println(i.M1(x))
     fmt.Println(i.M2(x))
    }
    

    playground

    *)更改 M1M2 以返回 int 而不是 struct 并使用接收器修复函数声明的语法

相关问题