Skip to content

Instantly share code, notes, and snippets.

@marcinwyszynski
Created March 6, 2014 00:12
Show Gist options
  • Save marcinwyszynski/9379500 to your computer and use it in GitHub Desktop.
Save marcinwyszynski/9379500 to your computer and use it in GitHub Desktop.
Golang: self-referential functions
// 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