I have code with interface:
package main
import (
"math"
"fmt"
)
type Circle struct {
x, y, r float64
}
type Rectangle struct {
x1, y1, x2, y2 float64
}
type Figure interface {
Area() float64
}
func (c *Circle) Area() float64 {
return math.Pi * c.r * c.r
}
func (r *Rectangle) Area() float64 {
return math.Abs(r.x2 - r.x1) * math.Abs(r.y2 - r.y1)
}
func main() {
figures := make([]Figure, 0)
figures = append(figures, &Circle{0, 0, 10})
figures = append(figures, &Rectangle{0, 0, 10, 20})
for _, figure := range figures {
fmt.Print(figure.Area(), "\n")
}
}
output:
314.159265
200
and code with only methods for my struct:
package main
import (
"math"
"fmt"
)
type Circle struct {
x, y, r float64
}
type Rectangle struct {
x1, y1, x2, y2 float64
}
func (c *Circle) Area() float64 {
return math.Pi * c.r * c.r
}
func (r *Rectangle) Area() float64 {
return math.Abs(r.x2 - r.x1) * math.Abs(r.y2 - r.y1)
}
func main() {
c := Circle{0,0,10}
r := Rectangle{0,0,10,20}
fmt.Print(c.Area(), "\n")
fmt.Print(r.Area(), "\n")
}
and the same output:
314.1592653589793
200
When I use interface I have extra code in the form of interfaces declaration. If the interfaces perfectly implement polymorphism in Go, why then the methods of structures? What plus from interfaces, where is the difference? May be my example not good. Thank you!