Skip to content

Instantly share code, notes, and snippets.

@mertenvg
Last active January 30, 2016 01:31
Show Gist options
  • Save mertenvg/5647e497585e6196f4a1 to your computer and use it in GitHub Desktop.
Save mertenvg/5647e497585e6196f4a1 to your computer and use it in GitHub Desktop.
Method values and method expressions play
// http://play.golang.org/p/YbcN6-hLq-
//
package main
import "fmt"
type Methoder interface{
Method()
}
type Methodable struct {
Name string
methodCalled bool
}
func (m *Methodable) Method() {
m.methodCalled = true
}
func (m Methodable) WasMethodCalled() bool {
return m.methodCalled
}
func showMethodableState(m *Methodable) {
if m.WasMethodCalled() {
fmt.Printf("Yup! Method() was called on %s\n", m.Name)
} else {
fmt.Printf("Nope! No Method() call on %s yet\n", m.Name)
}
}
func main() {
m1 := &Methodable{Name: "m1"}
m2 := &Methodable{Name: "m2"}
m3 := &Methodable{Name: "m3"}
// create method value from instance
me1 := m1.Method
// create method expression from type
me2 := (*Methodable).Method
// create method expression from interface
me3 := Methoder.Method
methods := []*Methodable{m1, m2, m3}
// Show initial state
fmt.Println("Initial state:")
for _, m := range methods {
showMethodableState(m)
}
// Call the method value
me1()
// Call the method expression.
// Require the receiver as the first parameter
me2(m2)
me3(m3)
// Show final state
fmt.Println("Final state:")
for _, m := range methods {
showMethodableState(m)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment