dongluan5740 2018-08-27 01:51
浏览 50
已采纳

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

I had written a lazy code to demonstrate the issue I am having to implement interfaces. I have methods M1, M2 that take struct X as an argument and have a type of struct Y. I wanted all these methods to be implemented by a single interface I. The issue is the method M that implements the interface I needs to be aware of the arguments that are required to be passed to the child methods (M1,M2). I get an error: <argument name> used as a value when I pass multiple arguments in 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条回答 默认 最新

  • dousong5161 2018-08-27 02:17
    关注

    The problem that cause <argument name> used as a value error in your example is that functions that form interface I are declared to have no return value:

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

    Surely you can't pass function-call as argument of Println if the function returns nothing: fmt.println(i.M1(x)). Change the interface declaration in your example to return something (and a few more fixes*):

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

    <kbd>playground</kbd>

    *) change M1 & M2 to return int instead of struct and fix syntax for function declaration with receiver

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据