Created
October 3, 2016 16:58
-
-
Save fegoa89/fe04caaf7a1175bf59fb1f8c861ad235 to your computer and use it in GitHub Desktop.
Some Golang notes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/////////////////////////////////////////////////////////////////////////////// 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