Created
August 2, 2014 15:03
-
-
Save tenntenn/8137f21e82fd18b16df9 to your computer and use it in GitHub Desktop.
[Go言語]structにinterfaceを埋め込んで,動的に入れ替えるパターン ref: http://qiita.com/tenntenn/items/92928990173514c2adea
This file contains 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" | |
"strings" | |
) | |
type StringerFunc func() string | |
func (sf StringerFunc) String() string { | |
return sf() | |
} | |
type Person struct { | |
fmt.Stringer | |
FirstName string | |
LastName string | |
Age int | |
} | |
func NewPerson(firstName, lastName string, age int) (p *Person) { | |
p = &Person{ | |
nil, | |
firstName, | |
lastName, | |
age, | |
} | |
p.Stringer = StringerFunc(func() string { | |
return fmt.Sprintf("%s %s (%d)", p.FirstName, p.LastName, p.Age) | |
}) | |
return | |
} | |
func (p *Person) SetStringer(sf func(p *Person) string) { | |
p.Stringer = StringerFunc(func() string { | |
return sf(p) | |
}) | |
} | |
func main() { | |
p := NewPerson("Taro", "Yamada", 20) | |
fmt.Println(p) | |
p.SetStringer(func(p *Person) string { | |
return fmt.Sprintf("%s, %s (%d)", strings.ToUpper(p.LastName), p.FirstName, p.Age) | |
}) | |
fmt.Println(p) | |
} |
This file contains 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
Taro Yamada (20) | |
YAMADA, Taro (20) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment