Last active
January 30, 2016 01:31
-
-
Save mertenvg/5647e497585e6196f4a1 to your computer and use it in GitHub Desktop.
Method values and method expressions play
This file contains hidden or 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
// 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