Method Overloading in Go: Restrictions on Argument Types
In Go, methods with the same name and arity (number of arguments) can operate on different types. However, if you attempt to move the receiver of such methods to the arguments, you will encounter a compile error.
Consider the following code:
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() }
This code successfully prints "A" and "B" to the console. However, if you modify the method signatures as follows:
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) }
You will encounter 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
Reason for the Restriction
Go does not support overloading of user-defined functions based on their argument types. This is in contrast to some other languages, such as C , which allow overloading based on both function name and argument types.
In Go, functions with the same name and arity must have identical signatures. If you want to "overload" a function on one parameter, you must use methods. For example, you could create a Print method for each of your structs:
func (a A) Print() { fmt.Println(a.Name) } func (b B) Print() { fmt.Println(b.Name) }
This approach allows you to use the same method name while preserving the type safety of your code.
The above is the detailed content of Why Doesn't Go Support Function Overloading Based on Argument Types?. For more information, please follow other related articles on the PHP Chinese website!