Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does method signature have to perfectly match interface method

Tags:

go

I began to learn Go and have trouble understanding the following:

package main

import "fmt"

type I interface {
    foo(interface {})
}

type S struct {}

func (s S) foo(i int) {
    fmt.Println(i)
}

func main() {
    var i I = S{}
    i.foo(2)
}

This fails with:

cannot use S literal (type S) as type I in assignment:
        S does not implement I (wrong type for foo method)
                have foo(int)
                want foo(interface {})

I don't understand why Go doesn't accept the foo(int) signature given the fact that int implements interface {}. Can anyone help with an explanation?

like image 817
kaspersky Avatar asked May 28 '16 23:05

kaspersky


People also ask

Why is it necessary for method signature in a class?

The method signatures help distinguish overloaded methods (methods with the same name) in a class. Return types are not included in overloading. Only method signatures should be used to distinguish overloaded methods.

Which is a valid method signature in an interface?

Which three are valid method signatures in an interface? private int getArea(); public float getVol(float x); public void main(String [] args);

What does a method signature consist of?

Method Signature According to Oracle, the method signature is comprised of the name and parameter types. Therefore, all the other elements of the method's declaration, such as modifiers, return type, parameter names, exception list, and body are not part of the signature.

CAN interfaces declare method signatures?

Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body). Interfaces specify what a class must do and not how.


1 Answers

I think your understanding of interface isn't sound. Interface{} itself is a type. It consists of two things : underlying type and underlying value.

Golang doesn't have overloading. Golang type system matches by name and requires consistency in the types

So, when you are defining a function taking a interface type as a parameter:

foo(interface {})

This is a different function from a function taking int type:

foo(int)

So you should change the following line to

func (s S) foo(i interface{}) {
    fmt.Println(i)
}

Or better yet to this:

type I interface {
    foo()
}

type S struct {
    I int
}

func (s S) foo() {
    fmt.Println(s.I)
}

func main() {
    var i I = S{2}
    i.foo()
}
like image 151
khrm Avatar answered Sep 22 '22 09:09

khrm