Go to inline method of child method call call instead of parent method

Here's an example Go code with an interface, parent structuring, and 2 child structures

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)
    }

}

I have the results:

$ 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

My problem is a call Shape.PrintAreathat calls a method Shape.Areafor Circle and Rectangle instead of calling methods Circle.Areaand Rectangle.Area.

Is this a bug in Go?

Thank you for your help.

+4
source share
1 answer

ShapeInterface.PrintArea() Circle, PrintArea() Circle. PrintArea() Rectangle, Shape.

, . Go is () - : , ; , struct, interface, .

, , : , PrintArea() "overridden" Area(), Go .

Shape.PrintArea() - Shape.Area(), , . Shape , , , "" .

: , x.f ( f ), , . :

  • f f T, f T. , f, T.
  • x T *T, T , x.f T, a f.

Circle: si.PrintArea() Circle.PrintArea(), :

func (c *Circle) PrintArea() {
    fmt.Printf("%s : Area %v\r\n", c.GetName(), c.Area())
}

c.Area() , c *Circle, *Circle , .

PrintArea(si) si.Area(). si Cicle Area() Circle, .

Rectangle si.PrintArea() Shape.PrintArea(), PrintArea() Rectangle ( *Rectangle). Shape.PrintArea() Shape.Area() Rectangle.Area() - , Shape Rectangle. ,

Rectangle1 : Area 0

Rectangle1 : Area 20.

PrintArea(si) ( Rectangle), si.Area(), Rectangle.Area(), .

+6

All Articles