Golang方法具有相同的名称和格式,但类型不同 [英] Golang methods with same name and arity, but different type
问题描述
以下代码正常工作。两种方法在两个不同的结构上运行并打印结构的字段:
type A struct {
Name string
type B struct {
名称字符串
}
func(a * A)Print(){
fmt .brintln(a.Name)
}
func(b * B)Print(){
fmt.Println(b.Name)
}
func main(){
a:=& A {A}
b:=& B {B}
a.Print()
b.Print()
}
显示所需的输出在控制台:
A
$现在,如果我按照以下方式更改方法签名,则会出现编译错误。我只是将方法的接收器移动到方法的参数中:
B
$ $ $ $ $ $ c $ func Print(a * A){
fmt.Println(a.Name)
}
func打印(b * B){
fmt.Println(b.Name)
}
func main(){
a:=& A {A}
b:=& B {B}
打印(a)
打印(b)
}
我无法甚至编译该程序:
./ test.go:22:在此块中重新声明的打印
先前的声明在。 /test.go:18
./test.go:40:在函数参数
问题:为什么我可以在接收器中交换结构类型,但不能在
参数中交换,方法具有相同的名称和参数?
因为Go不支持在其参数类型上重载用户定义函数。
您可以使用不同名称创建函数,或者如果您只想在一个参数(接收方)上重载,可以使用方法。
The following code works fine. Two methods operating on two different structs and printing a field of the struct:
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()
}
Shows the desired output in the console:
A
B
Now, if I change the method signature in the following way I get an compile error. I just move the receiver of the method to the arguments of the method:
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)
}
I can't even compile the program:
./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
Question: Why is it, that I can interchange struct types in the receiver, but not in the arguments, when the methods have the same name and arity?
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).
这篇关于Golang方法具有相同的名称和格式,但类型不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!