Search⌘ K

Solution Review: Advancing the Shapes Analysis

Explore how to implement and use Go interfaces by creating types for shapes such as Triangle and Square. Learn to define methods like Area and Perimeter, assign these to interface variables, and leverage type assertions to write flexible, reusable code in Go.

We'll cover the following...
Go (1.6.2)
package main
import "fmt"
type Square struct {
side float32
}
type Triangle struct {
base float32
height float32
}
type AreaInterface interface {
Area() float32
}
type PeriInterface interface {
Perimeter() float32
}
func main() {
var areaIntf AreaInterface
var periIntf PeriInterface
sq1 := new(Square)
sq1.side = 5
tr1 := new(Triangle)
tr1.base = 3
tr1.height = 5
areaIntf = sq1
fmt.Printf("The square has area: %f\n", areaIntf.Area())
periIntf = sq1
fmt.Printf("The square has perimeter: %f\n", periIntf.Perimeter())
areaIntf = tr1
fmt.Printf("The triangle has area: %f\n", areaIntf.Area())
}
func (sq *Square) Area() float32 {
return sq.side * sq.side
}
func (sq *Square) Perimeter() float32 {
return 4 * sq.side
}
func (tr *Triangle) Area() float32 {
return 0.5 * tr.base*tr.height
}

From line 8 to line 11, we implement the Triangle type: from the formula for the area, we see that it needs two fields base and height, both of type float32.

See the implementation of PeriInterface from line 17 to line 18: it needs a function Perimeter(), that also returns a float32.

From line 48 to line 50, the Triangle ...