Abstract type with interface


(Che) #1

Hello, why does this code not yield an Area of 1 for all objects that implement Shaper by embedding the Shape ‘abstract’ type?

https://play.golang.org/p/Cg_Lm6Stj6Q

I’m trying to solve the exercise 11.2.3 from “The Way to Go”. Unfortunately it does not provide any solution. The text is as follows
“Now we will implement the same functionality by using an ‘abstract’ type Shape (abstract
because it has no fields) which implements Shaper, and embedding his type in the other
types. Now demonstrate that overriding is used as explained in § 10.6.5: interfaces_
poly3.go”


(George Calianu) #2

I simplified for you the previous example to understand how things works.

package main

type Shape struct {}

type Rectangle struct {
    Shape
}

func (r Rectangle) Area() {
    println(1)
}

func (s Shape) Area() {
    println(2)
}

func main() {
    var s Shape
    r := Rectangle{s}
    r.Area()
    r.Shape.Area()
}

https://play.golang.org/p/wodgOCLjJz4