Created
July 13, 2011 17:38
-
-
Save bradfitz/1080828 to your computer and use it in GitHub Desktop.
Go optional args, v2
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" | |
) | |
type Person struct { | |
Name string | |
Age int | |
Position string | |
Department string | |
} | |
type PersonArg interface { | |
AddArg(*Person) | |
} | |
type Age int | |
func (age Age) AddArg(p *Person) { | |
p.Age = int(age) | |
} | |
type Position string | |
func (pos Position) AddArg(p *Person) { | |
p.Position = string(pos) | |
} | |
type Department string | |
func (dep Department) AddArg(p *Person) { | |
p.Department = string(dep) | |
} | |
func (p *Person) String() string { | |
// terrible. | |
pos := "" | |
if p.Position != "" { | |
pos = " - " + p.Position | |
} | |
dept := "" | |
if p.Department != "" { | |
dept = " " + p.Department | |
} | |
if p.Age == 0 { | |
return p.Name + pos + dept | |
} | |
return fmt.Sprintf("%s (%d)%s%s", p.Name, p.Age, pos, dept) | |
} | |
func NewPerson(name string, args ...PersonArg) *Person { | |
p := &Person{Name: name} | |
for _, a := range args { | |
a.AddArg(p) | |
} | |
return p | |
} | |
func main() { | |
p := fmt.Println | |
p(NewPerson("Steve")) | |
p(NewPerson("Ajay", | |
Department("Skunkworks"), | |
Position("Engineer"))) | |
p(NewPerson("Dave", | |
Age(43), | |
Position("Tester"))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, I proposed that awhile back too and was shot down.