Skip to content

Instantly share code, notes, and snippets.

@bradfitz
Created July 13, 2011 17:38
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradfitz/1080828 to your computer and use it in GitHub Desktop.
Save bradfitz/1080828 to your computer and use it in GitHub Desktop.
Go optional args, v2
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")))
}
@bradfitz
Copy link
Author

Yes, I proposed that awhile back too and was shot down.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment