Golang methods with same name and arity, but different type

You can not do function or method overloading in Go. You can have two methods with the same names in Go but the receiver of these methods must be of different types. you can see more in this link .


Because Go does not support overloading of user-defined functions on their argument types.

You can make functions with different names instead, or use methods if you want to "overload" on only one parameter (the receiver).


You can use type introspection. As a general rule, though, any use of the generic interface{} type should be avoided, unless you are writing a large generic framework.

That said, a couple of ways to skin the proverbial cat:

Both methods assume a Print() method is defined for both types (*A and *B)

Method 1:

func Print(any interface{}) {
    switch v := any.(type) {
    case *A:
        v.Print()
    case *B:
        v.Print()
    default:
        fmt.Printf("Print() invoked with unsupported type: '%T' (expected *A or *B)\n", any)
        return
    }
}

Method 2:

type Printer interface {
    Print()
}

func Print(any interface{}) {
    // does the passed value honor the 'Printer' interface
    if v, ok := any.(Printer); ok {
        // yes - so Print()!
        v.Print()
    } else {
        fmt.Printf("value of type %T passed has no Print() method.\n", any)
        return
    }
}

If it's undesirable to have a Print() method for each type, define targeted PrintA(*A) and PrintB(*B) functions and alter Method 1 like so:

    case *A:
        PrintA(v)
    case *B:
        PrintB(v)

Working playground example here.

Tags:

Methods

Struct

Go