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

这是带有接口、父结构和 2 个子结构的 Go 代码示例


package main


import (

    "fmt"

    "math"

)


// Shape Interface : defines methods

type ShapeInterface interface {

    Area() float64

    GetName() string

    PrintArea()

}


// Shape Struct : standard shape with an area equal to 0.0

type 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 method

type 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 Interface

func  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 methods

func 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.go

Shape1 : Area 0

Interface => Shape1 : Area 0

Circle1 : Area 314.1592653589793

Interface => Circle1 : Area 314.1592653589793

Rectangle1 : Area 0

Interface => Rectangle1 : Area 20

我的问题是调用圆和矩形的Shape.PrintArea哪个调用Shape.Area方法而不是调用Circle.Area和Rectangle.Area方法。


这是 Go 中的错误吗?


红颜莎娜
浏览 189回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python