Skip to content

Instantly share code, notes, and snippets.

@bojand
Created April 4, 2018 12:05
Show Gist options
  • Save bojand/e2db938e93c070ff10bd76bcf1321d72 to your computer and use it in GitHub Desktop.
Save bojand/e2db938e93c070ff10bd76bcf1321d72 to your computer and use it in GitHub Desktop.
Method override in Go
package main
import (
"fmt"
"strings"
)
type Cap struct {
message string
}
func (c *Cap) Do() string {
return strings.ToUpper(c.message)
}
func (c *Cap) GetMessage() string {
return c.message
}
// Embed Cap
type Greet struct {
greeting string
Cap
}
// Use embedded implementation
func (g *Greet) Do() string {
superVal := g.Cap.Do()
return fmt.Sprintf("%s %s!", g.greeting, superVal)
}
// Embed Cap
type Repeat struct {
count int
Cap
}
// Completely override embedded imlementation
func (r *Repeat) Do() string {
return strings.Repeat(r.Cap.GetMessage(), r.count)
}
func main() {
capper := Cap{"Bob"}
fmt.Printf("capper.Do(): %+v\n", capper.Do())
greeter := Greet{"Hello", capper}
fmt.Printf("greeter.Do(): %+v\n", greeter.Do())
greeter2 := Greet{"Bye", Cap{"Kate"}}
fmt.Printf("greeter2.Do(): %+v\n", greeter2.Do())
repeater := Repeat{3, Cap{"Anne "}}
fmt.Printf("repeater.Do(): %+v\n", repeater.Do())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment