Skip to content

Instantly share code, notes, and snippets.

@squarism
Created June 14, 2013 19:18
Show Gist options
  • Save squarism/5784474 to your computer and use it in GitHub Desktop.
Save squarism/5784474 to your computer and use it in GitHub Desktop.
I'm pretty sure I'm writing unidiomatic go. But the official docs claim that structs work like OO classes do.
// You have to have your GOPATH and all that set up for this source file separation
// to work. I was playing with source file organization at the same time.
// If this is too annoying, I can rework it.
// car/car.go
package main
import (
"car/parts"
"fmt"
)
var color string = "blue"
type Warranty struct {
years int
miles float32
}
type Car struct {
sMake string
model string
// doors []parts.Door // forget about this for now
engine *parts.Engine
}
func init() { // optional init of package
// var v6 = &parts.Engine{6, false}
}
func main() {
car := Car{
sMake: "Ford",
model: "Mustang",
engine: &parts.Engine.NewEngine(6),
}
fmt.Printf("I'm going to work now in my %s %s\n", car.sMake, car.model)
fmt.Println("I guess I should start my car.")
car.Start()
fmt.Println("Engine started?", car.engine.IsStarted())
}
func (car Car) Start() {
fmt.Println("starting engine ...")
car.engine.Start()
fmt.Println("you'd think it would be started here ...", car.engine)
}
// car/parts/engine.go
package parts
import (
"fmt"
)
type Engine struct {
cylinders int
started bool
}
// go does not have explicit constructors
func NewEngine(cylinders int) *Engine {
return &Engine{cylinders: cylinders, started: false}
}
func (engine Engine) Start() {
fmt.Println("ENGINE STARTED", engine.started)
engine.started = true
fmt.Println("ENGINE STARTED", engine.started)
}
func (engine Engine) IsStarted() bool {
return engine.started
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment