Skip to content

Instantly share code, notes, and snippets.

@jochasinga
Last active August 29, 2015 14:07
Show Gist options
  • Save jochasinga/7f1f195a5330e77d8c94 to your computer and use it in GitHub Desktop.
Save jochasinga/7f1f195a5330e77d8c94 to your computer and use it in GitHub Desktop.
Inheriting and reusing through structs and interfaces in Go
package main
import(
"fmt"
"io/ioutil"
"os"
)
type Greeter interface {
Greet()
}
type Man struct {
language string
// other factors to decide if the girl would like you (for fun)
lame, nationality, build, eye_color string
age, height uint8
// you could be in debt, so we can't rule out negative values
income int64
// this is to remind her you are available
married bool
}
type Woman struct {
// Woman now has Man's fields, with her own one
Man
hair_style string
}
func (m Man) Greet() {
switch m.language {
case "British" : fmt.Println("Good morning, dear")
case "American": fmt.Println("Mornin' there")
case "Japanese": fmt.Println("Ohayou Gozaimasu")
case "Thai" : fmt.Println("Arunsawad Krub")
default : fmt.Println("Good morning")
}
}
// Additional function to let our girl friend write a love letter
func writeFile(msg string) {
defer func() {
str := recover()
fmt.Println(str)
}()
// Create and write msg to a file
d := []byte(msg + "\n")
f, err := os.Create("loveLetter.txt")
defer f.Close()
err = ioutil.WriteFile("loveLetter.txt", d, 0644)
if err != nil {
panic("File not written!")
} else {
// get the file's rooted path
dir, e := os.Getwd()
if e != nil {
panic("Can't get the path!")
} else {
fmt.Printf("File written to %s", dir + "loveLetter.txt\n")
}
}
}
func (w Woman) Greet() {
// In addition to greeting by talking, a shy Woman will want to write too
switch w.language {
case "British" : writeFile("Good morning, dear")
case "American": writeFile("Mornin' there")
case "Japanese": writeFile("Ohayou Gozaimasu")
case "Thai" : writeFile("Arunsawad Krub")
case "Tagalog" : writeFile("Magandang Umaga")
default : writeFile("Good morning")
}
}
func main() {
jay := Man{language: "Japanese"}
james := Man{language: "Thai"}
john := Man{language: "British"}
// It just happens that jennifer's newly inherited field
// language doesn't initialize using struct literal
// perhaps because jennifer needs to be a pointer like so
jennifer := new(Woman)
jennifer.language = "Tagalog"
greeters := [...]Greeter{jay, james, john, jennifer}
for i := range greeters {
greeters[i].Greet()
}
// The guy greeters will print out greeting, while jennifer will write it instead
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment