dongwei1234 2018-08-23 04:26
浏览 16

基于接收者,我如何拥有具有不同返回类型的方法?

I have the following interface:

type ExampleInterface interface{
    GetFirstItemInSlice()
}

func GetFirstItemInSlice(slice ExampleInterface){
    slice.GetFirstItemInSlice()
}

func (slice IntSlice) GetFirstItemInSlice(){
    // Omitted for brevity.
}

func (slice StringSlice) GetFirstItemInSlice(){
    // Omitted for brevity.
}

Now, it is clear here, that my two functions which have recievers (the bottom two), will want to return different types, one a string, and the other, an int. If I just tack on a return type, then it will break my interface, right?

I assume this is a common problem, and I am missing some key knowledge component on interfaces, All help appreciated.

Please note : I would rather not return an interface, I would REALLY love to return a piece of typed data.

  • 写回答

1条回答 默认 最新

  • droc60607 2018-08-23 07:19
    关注

    How might I have methods with different return types based on the reciever?

    TL;DR; You can't.

    Longer answer: There are roughly three options to accomplish what you're describing. You probably won't like any of them.

    1. Return an interface

      type ExampleInterface interface{
          GetFirstItemInSlice() interface{}
      }
      

      Then, of course, it's up to each caller to assert back to the underlying type.

    2. Use different return types.

      type IntInterface interface{
          GetFirstIntInSlice() int
      }
      
      type StringInterface interface {
          GetFirstStringSlice() string
      }
      
    3. Don't return, but instead use reflection to modify a passed in variable.

      type ExampleInterface interface{
          GetFirstItemInSlice(interface{})
      }
      

      This is the most complex one to write, and is almost certainly overkill for something as simple as returning an int or a slice. But it does have use for more complex data structures, and is the approach taken by things like the standard library's json unmarshaling. In this case, the caller would pass in a pointer to an allocated variable, which the method would then set, using reflection. The calling code might look like:

      var foo int
      ei.GetFirstItemInSlice(&foo)
      

    A fourth option, and probably the best in your particular situation, is a refactor so that none of the above is necessary. Without understanding your larger problem, though, I cannot offer a specific, concrete suggestion on how to do this in your case.

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集