Home >Backend Development >Golang >Can Go Methods Be Overloaded Based on Argument Types?

Can Go Methods Be Overloaded Based on Argument Types?

Susan Sarandon
Susan SarandonOriginal
2024-12-22 16:08:13804browse

Can Go Methods Be Overloaded Based on Argument Types?

Method Overloading in Golang with Different Types

In Go, it is possible to define methods with the same name but different types for their receivers, allowing for polymorphic behavior. However, this is not the case for arguments.

When using receiver-based methods, as seen in the code snippet below:

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)
}

This compiles successfully and provides the desired output when calling the Print method on instances of A and B. However, when attempting to move the receiver of the method to the arguments, as shown:

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

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

This results in a compile error:

./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

This is because Go does not support function overloading based on argument types. This means that functions with the same name cannot be defined with different argument types. Instead, it requires functions to have unique names or to use methods if you want to "overload" on only one parameter, the receiver.

Therefore, it is permissible to overload methods based on the receiver but not on the argument types.

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

Statement:
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