From f7141774a6ea414bdd4acacf96a461fd39648ba6 Mon Sep 17 00:00:00 2001 From: Billy Hinners Date: Mon, 27 Feb 2017 12:39:25 -0500 Subject: [PATCH] Example of O-O in Go using embedded struct and interface --- carvalue.go | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 carvalue.go diff --git a/carvalue.go b/carvalue.go new file mode 100644 index 0000000..efb9e0a --- /dev/null +++ b/carvalue.go @@ -0,0 +1,57 @@ +package main + +import ( + "fmt" +) + +type CarValue interface { + value() float64 +} + +type Car struct { + Make string + Year int +} + +func (c *Car) value() float64 { + switch { + case c.Year >= 2000 && c.Year < 2010: + return 6500 + case c.Year >= 2010 && c.Year < 2020: + return 9000 + default: + return 3000 + } +} + +func NewCar(make string, year int) *Car { + return &Car{make, year} +} + +type Tesla struct { + Car +} + +func (t *Tesla) value() float64 { + switch { + case t.Year >= 2010 && t.Year < 2015: + return 18000 + default: + return 24000 + } +} + +func NewTesla(year int) *Tesla { + return &Tesla{*NewCar("Tesla", year)} +} + +func value(c CarValue) float64 { + return c.value() +} + +func main() { + herbie := NewCar("Volkswagen", 1963) + model3 := NewTesla(2017) + fmt.Println("Herbie is worth", value(herbie)) + fmt.Println("Model3 is worth", value(model3)) +}