Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example of O-O in Go using embedded struct and interface #14

Merged
merged 1 commit into from
Mar 4, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions carvalue.go
Original file line number Diff line number Diff line change
@@ -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))
}