Reputation: 427
I am learning Go and am trying to fully understand how to use interfaces in Go.
In the book The Way to Go, there is an example listing 11.1 (pages 264-265). I feel that I am definitely missing something in my understanding of it. The code runs fine, but I do not understand what effect (if any) the interface is having on the struct and method.
package main
import "fmt"
type Shaper interface {
Area() float32
}
type Square struct {
side float32
}
func (sq *Square) Area() float32 {
return sq.side * sq.side
}
func main() {
sq1 := new(Square)
sq1.side = 5
// var areaIntf Shaper
// areaIntf = sq1
// shorter, without separate declaration:
// areaIntf := Shaper(sq1)
// or even:
areaIntf := sq1
fmt.Printf("The square has area: %f\n", areaIntf.Area())
}
Upvotes: 1
Views: 50
Reputation: 11626
In that example, it has no effect.
Interfaces allow different types to adhere to a common contract, allowing you to create generalized functions.
Here's a modified example on Play
Notice the printIt function, it can take any type that adheres to the Shaper interface.
Without interfaces, you would have had to make printCircle and printRectangle methods, which doesn't really work as you add more and more types to your application over time.
package main
import (
"fmt"
"math"
)
type Shaper interface {
Area() float32
}
type Square struct {
side float32
}
func (sq *Square) Area() float32 {
return sq.side * sq.side
}
type Circle struct {
radius float32
}
func (c *Circle) Area() float32 {
return math.Pi * c.radius * c.radius
}
func main() {
sq1 := new(Square)
sq1.side = 5
circ1 := new(Circle)
circ1.radius = 5
var areaIntf Shaper
areaIntf = sq1
// areaIntf = sq1
// shorter, without separate declaration:
// areaIntf := Shaper(sq1)
// or even:
fmt.Printf("The square has area: %f\n", areaIntf.Area())
areaIntf = circ1
fmt.Printf("The circle has area: %f\n", areaIntf.Area())
// Here is where interfaces are actually interesting
printIt(sq1)
printIt(circ1)
}
func printIt(s Shaper) {
fmt.Printf("Area of this thing is: %f\n", s.Area())
}
Upvotes: 1