Hi All,
In this script, I started to apply interface in the structs.
type Circle struct {
x float64
y float64
r float64
}
type Rectangle struct {
x1, y1, x2, y2 float64
}
type Shape interface {
area() float64
}
type MultiShape struct {
shapes []Shape
}
func distance(x1, y1, x2, y2 float64) float64 {
a := x2 - x1
b := y2 - y1
return math.Sqrt(a*a + b*b)
}
func (c *Circle) area() float64 { \\ when I take out this `*`, this scripts worked
return math.Pi * c.r * c.r
}
func (r *Rectangle) area() float64 { \\ when i took out this `*`, this scripts worked
l := distance(r.x1,r.y1, r.x1, r.y2)
w := distance(r.x1,r.y1, r.x2, r.y1)
return l * w
}
func (m *MultiShape) area() float64 {
var area float64
for _, s := range m.shapes {
area += s.area()
}
return area
}
func main() {
multiShape := MultiShape{[]Shape{
Circle{0,0,5},
Rectangle{0,0,10,10},
},}
fmt.Println(multiShape.area())
}
However, after running this scripts, i got following errors.
./Chapter7.go:93: cannot use Circle literal (type Circle) as type Shape in array or slice literal:
Circle does not implement Shape (area method has pointer receiver)
./Chapter7.go:94: cannot use Rectangle literal (type Rectangle) as type Shape in array or slice literal:
Rectangle does not implement Shape (area method has pointer receiver)
If I think this correctly, Circle{0,0,5}
or Rectangle{0,0,10,10}
because they are in type of []Shape
and the methods area()
is under type Shape interface
, so I thought we don’t need to add &
to Circle{0,0,5}
or Rectangle{0,0,10,10}
to call func
with pointer
type because it is called with method area()
.
But in this case, when i took out *
from func func (c *Circle)
or func (r *Rectangle)
, it worked without error. Could anyone have any ideas about this?