Last active
July 30, 2023 16:17
-
-
Save mahiro72/6fd3569e536a055b733ef6ad53a4ccf0 to your computer and use it in GitHub Desktop.
self-referential functions practice
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
package main | |
import "fmt" | |
type Cat struct { | |
Name string | |
Age int | |
} | |
type catOpt func(c *Cat) catOpt | |
func (c *Cat) Options(opts ...catOpt) []catOpt { | |
var prevOpts []catOpt | |
for _,opt := range opts { | |
prevOpts = append(prevOpts, opt(c)) | |
} | |
return prevOpts | |
} | |
func SetName(name string) catOpt { | |
return func(c *Cat) catOpt { | |
prev := c.Name | |
c.Name = name | |
return SetName(prev) | |
} | |
} | |
func SetAge(age int) catOpt { | |
return func(c *Cat) catOpt { | |
prev := c.Age | |
c.Age = age | |
return SetAge(prev) | |
} | |
} | |
func main() { | |
cat := &Cat{Name: "hana",Age: 1} | |
fmt.Printf("%+v\n",cat) //&{Name:hana Age:1} | |
f(cat) | |
fmt.Printf("%+v\n",cat) //&{Name:hana Age:1} | |
f2(cat) | |
fmt.Printf("%+v\n\n",cat) //&{Name:hana Age:1} | |
} | |
func f(cat *Cat) { | |
prev := cat.Options(SetName("kinako")) | |
defer cat.Options(prev...) | |
fmt.Printf("%+v\n",cat) //&{Name:kinako Age:1} | |
} | |
func f2(cat *Cat) { | |
prev := cat.Options(SetName("mike"),SetAge(2)) | |
fmt.Printf("%+v\n",cat) //&{Name:mike Age:2} | |
prev2 := cat.Options(prev...) | |
fmt.Printf("%+v\n",cat) //&{Name:hana Age:1} | |
prev3 := cat.Options(prev2...) | |
fmt.Printf("%+v\n",cat) //&{Name:mike Age:2} | |
defer cat.Options(prev3...) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
error