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

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.

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.