r := Rectangle{5, 3} // Area() of Rectangle needs a value q := &Square{5} // Area() of Square needs a pointer // shapes := []Shaper{Shaper(r), Shaper(q)} // or shorter shapes := []Shaper{r, q} fmt.Println("Looping through shapes for area ...") for n, _ := range shapes { fmt.Println("Shape details: ", shapes[n]) fmt.Println("Area of this shape is: ", shapes[n].Area()) } }
funcmain() { r := Rectangle{5, 3} // Area() of Rectangle needs a value q := &Square{5} // Area() of Square needs a pointer shapes := []Shaper{r, q} // 创建一个接口列表 并不关心它是什么类型的。 fmt.Println("Looping through shapes for area ...") for n, _ := range shapes { fmt.Println("Shape details: ", shapes[n]) fmt.Println("Area of this shape is: ", shapes[n].Area()) } topgen := []TopologicalGenus{r, q} fmt.Println("Looping through topgen for rank ...") for n, _ := range topgen { fmt.Println("Shape details: ", topgen[n]) fmt.Println("Topological Genus of this shape is: ", topgen[n].Rank()) } }
空接口和函数重载
Go 中的函数重载是不被允许的。但是在 Go 中可以通过可变参数 …T 作为函数的最后一个参数来实现。如果我们将 T 变为空接口,那么其实 T 是可以为任何类型的,这样就允许我们传递任何数量任何类型的参数给函数,即为重载的意义:
1
fmt.Printf(format string, a ...interface{})(n int, errno error)