Functions with different return in Go

Asked

Viewed 139 times

1

I need to create an interface that contains a method decode(), but I need it to return different things to every struct that uses this method, and I don’t know how to do that.

type teste interface {
    x()
}

type A struct {
}

type B struct {
}

func (a A) x() int{
    return 2
}

func (b B) x() string{
    return "b"
}

func main(){
    var t, tt teste
    t = A{}
    tt = B{}
    fmt.Println(t.x(), tt.x())
}

in an hour he should return int and in the other string, but it doesn’t work. There’s some way to do this?

1 answer

4


The method declaration in the interface as shown is an invalid syntax, you need to declare the whole signature of the method. And doing this can only conform to the interface if you implement a method that is exactly equal to the interface, there can be no difference.

Go doesn’t have that. Especially since it has no inheritance and thus covariance, in the case of the type of return.

But if you think conceptually, in the form presented in the question, it doesn’t even make sense, they’re really different methods with no relation to each other, even if you think you do, it’s just an evaluation error (and look, I’m looking at an artificial example and I’ve figured it out).

It’s not that it’s totally impossible to build something like this, but you would have to use a complex mechanism that creates an object that can contain any of that data. It doesn’t usually pay off, it creates other problems, and if you really need it, it might be an indication that you’re using the wrong language for the task, but I’m just saying this hypothetically.

The right thing seems to be to have two different interfaces. Interfaces should be the contract for the same thing, if the result produced is not the same then the interface is not the same. You can see more in Principle of Liskov’s replacement.

It is possible that there are even other conceptual errors, but the question dealt with too abstractly to talk about.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.