2014-05-15 161 views
8

以下代码可正常工作。两种方法在两个不同的结构操作和打印结构的一个字段:具有相同名称和元素但类型不同的Golang方法

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 

问题:为什么,我可以互换结构类型在接收方中,但不在 参数中,方法具有相同的名称和参数?

回答

22

由于Go不支持在其参数类型上重载用户定义的函数。

只能通过方法,开关,类型开关和通道实现多态。

+1

谢谢。刚刚发现它:http://golang.org/doc/faq#overloading – Kiril

相关问题