Created
March 6, 2014 00:12
-
-
Save marcinwyszynski/9379500 to your computer and use it in GitHub Desktop.
Golang: self-referential functions
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
// Original idea: | |
// http://commandcenter.blogspot.nl/2014/01/self-referential-functions-and-design.html | |
package main | |
import "fmt" | |
type Cat struct { | |
Name string | |
} | |
func (c *Cat) SetName(opt CatOpt) CatOpt { | |
return opt(c) | |
} | |
type CatOpt func(c *Cat) CatOpt | |
func Name(newName string) CatOpt { | |
return func(c *Cat) CatOpt { | |
previousName := c.Name | |
c.Name = newName | |
return Name(previousName) | |
} | |
} | |
func main() { | |
c := &Cat{Name: "Filemon"} | |
fmt.Printf("%#v\n", c) | |
prevName := c.SetName(Name("Marcin")) | |
fmt.Printf("%#v\n", c) | |
c.SetName(prevName) | |
fmt.Printf("%#v\n", c) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment