How are interfaces used in the code example 11.1 from the book The Way to Go? -
i learning go , trying understand how use interfaces in go.
in book way go, there example listing 11.1 (pages 264-265). feel missing in understanding of it. code runs fine, not understand effect (if any) interface having on struct , 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()) }
in example, has no effect.
interfaces allow different types adhere common contract, allowing create generalized functions.
here's modified example on play
notice printit function, can take type adheres shaper interface.
without interfaces, have had make printcircle , printrectangle methods, doesn't work add more , more types application on 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 interfaces interesting printit(sq1) printit(circ1) } func printit(s shaper) { fmt.printf("area of thing is: %f\n", s.area()) }
Comments
Post a Comment