I've recently taken a liking to the Go programming language, I've found it wonderful so far but am really struggling to understand interfaces. I've read about quite a bit about them, but they still seem very abstract to me.
I've wrote a quick bit of code that uses an interface below:
package main
import (
"fmt"
"math"
)
type Circer interface {
Circ() float64
}
type Square struct {
side float64
}
type Circle struct {
diam, rad float64
}
func (s *Square) Circ() float64 {
return s.side * 4
}
func (c *Circle) Circ() float64 {
return c.diam * math.Pi
}
func (c *Circle) Area() float64 {
if c.rad == 0 {
var rad = c.diam / 2
return (rad*rad) * math.Pi
} else {
return (c.rad*c.rad) * math.Pi
}
}
func main() {
var s = new(Square)
var c = new(Circle)
s.side = 2
c.diam = 10
var i Circer = s
fmt.Println("Square Circ: ", i.Circ())
i = c
fmt.Println("Circle Circ: ", i.Circ())
}
I can't really see the purpose of the Circer interface. The methods are already written and I could save two lines of code by simply calling them directly on the structs, rather than using Circer as a wrapper.
Is there something I'm missing? Am I using the interface incorrectly? Any help or examples are appreciated.