【发布时间】:2021-10-05 23:05:02
【问题描述】:
以下代码可以正常工作。两种方法在两个不同的结构上运行并打印结构的一个字段:
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()
}
在控制台中显示所需的输出:
A
B
现在,如果我按以下方式更改方法签名,则会出现编译错误。我只是将方法的接收者移到方法的参数中:
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)
}
我什至无法编译程序:
./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
为什么我可以在接收器中交换结构类型,但不能在接收器中交换 参数,当方法具有相同的名称和数量?
【问题讨论】:
-
这不是作者想要做的。