Home > Backend Development > Golang > Can Go Overload Methods with Different Argument Types?

Can Go Overload Methods with Different Argument Types?

Susan Sarandon
Release: 2024-12-02 00:29:13
Original
219 people have browsed it

Can Go Overload Methods with Different Argument Types?

Overloading Methods with Different Types in Go

In Go, it is possible to define methods with the same name but different receiver types. For example, the following code works fine:

type A struct {
    Name string
}

type B struct {
    Name string
}

func (a *A) Print() {
    fmt.Println(a.Name)
}

func (b *B) Print() {
    fmt.Println(b.Name)
}

func main() {
    a := &A{"A"}
    b := &B{"B"}

    a.Print()
    b.Print()
}
Copy after login

This code prints the desired output:

A
B
Copy after login

However, if we change the method signature to move the receiver to the arguments of the method, we get a compile error:

func Print(a *A) {
    fmt.Println(a.Name)
}

func Print(b *B) {
    fmt.Println(b.Name)
}

func main() {
    a := &A{"A"}
    b := &B{"B"}

    Print(a)
    Print(b)
}
Copy after login

The compile error is:

./test.go:22: Print redeclared in this block
    previous declaration at ./test.go:18
./test.go:40: cannot use a (type *A) as type *B in function argument
Copy after login

The reason for this error is that Go does not support overloading of user-defined functions on their argument types. This means that we cannot have two functions with the same name but different argument types.

Instead, we can use different function names or use methods to "overload" on only one parameter (the receiver).

The above is the detailed content of Can Go Overload Methods with Different Argument Types?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template