为了账号安全,请及时绑定邮箱和手机立即绑定

去嵌入结构调用子方法而不是父方法

去嵌入结构调用子方法而不是父方法

红颜莎娜 2021-09-27 16:06:28
这是带有接口、父结构和 2 个子结构的 Go 代码示例package mainimport (    "fmt"    "math")// Shape Interface : defines methodstype ShapeInterface interface {    Area() float64    GetName() string    PrintArea()}// Shape Struct : standard shape with an area equal to 0.0type Shape struct {    name string}func (s *Shape) Area() float64 {    return 0.0}func (s *Shape) GetName() string {    return s.name}func (s *Shape) PrintArea() {    fmt.Printf("%s : Area %v\r\n", s.name, s.Area())}// Rectangle Struct : redefine area methodtype Rectangle struct {    Shape    w, h float64}func (r *Rectangle) Area() float64 {    return r.w * r.h}// Circle Struct : redefine Area and PrintArea method type Circle struct {    Shape    r float64}func (c *Circle) Area() float64 {    return c.r * c.r * math.Pi}func (c *Circle) PrintArea() {    fmt.Printf("%s : Area %v\r\n", c.GetName(), c.Area())}// Genreric PrintArea with Interfacefunc  PrintArea (s ShapeInterface){    fmt.Printf("Interface => %s : Area %v\r\n", s.GetName(), s.Area())}//Main Instruction : 3 Shapes of each type//Store them in a Slice of ShapeInterface//Print for each the area with the call of the 2 methodsfunc main() {    s := Shape{name: "Shape1"}    c := Circle{Shape: Shape{name: "Circle1"}, r: 10}    r := Rectangle{Shape: Shape{name: "Rectangle1"}, w: 5, h: 4}    listshape := []c{&s, &c, &r}    for _, si := range listshape {        si.PrintArea() //!! Problem is Witch Area method is called !!         PrintArea(si)    }}我有结果:$ go run essai_interface_struct.goShape1 : Area 0Interface => Shape1 : Area 0Circle1 : Area 314.1592653589793Interface => Circle1 : Area 314.1592653589793Rectangle1 : Area 0Interface => Rectangle1 : Area 20我的问题是调用圆和矩形的Shape.PrintArea哪个调用Shape.Area方法而不是调用Circle.Area和Rectangle.Area方法。这是 Go 中的错误吗?
查看完整描述

2 回答

  • 2 回答
  • 0 关注
  • 188 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信