Skip to content

Instantly share code, notes, and snippets.

@fegoa89
Created October 3, 2016 16:58
Show Gist options
  • Save fegoa89/fe04caaf7a1175bf59fb1f8c861ad235 to your computer and use it in GitHub Desktop.
Save fegoa89/fe04caaf7a1175bf59fb1f8c861ad235 to your computer and use it in GitHub Desktop.
Some Golang notes
/////////////////////////////////////////////////////////////////////////////// Inheritance
package main
import "fmt"
type Vehicle struct {
wheelCount int
}
// Define a behavior for Vehicle
func (vehicle Vehicle) numberOfWheels() int {
return vehicle.wheelCount
}
type Bike struct {
// Anonymous field Vehicle
Vehicle
}
func main() {
bike := Bike{ Vehicle{ 2 } }
// No method defined for Bike, but we have the same behavior as Vehicle.
fmt.Println("A Bike has this many wheels: ", bike.numberOfWheels())
}
/////////////////////////////////////////////////////////////////////////////// Constructor
package main
import "fmt"
type Rectangle struct {
Name string
Width, Height float64
}
func main() {
var a Rectangle
var b = Rectangle{"I'm b.", 10, 20}
var c = Rectangle{Height: 12, Width: 14}
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
}
/////////////////////////////////////////////////////////////////////////////// Interface
package main
import (
"fmt"
)
type Animal interface {
Speak() string
}
type Dog struct {
}
func (d Dog) Speak() string {
return "Woof!"
}
type Cat struct {
}
func (c Cat) Speak() string {
return "Meow!"
}
type Llama struct {
}
func (l Llama) Speak() string {
return "LaLLamaQueLLama!"
}
func main() {
animals := []Animal{Dog{}, Cat{}, Llama{}}
for _, animal := range animals {
fmt.Println(animal.Speak())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment