Skip to content

Instantly share code, notes, and snippets.

@poying
Created September 3, 2014 23:53
Show Gist options
  • Save poying/df50195b71350e233d40 to your computer and use it in GitHub Desktop.
Save poying/df50195b71350e233d40 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"reflect"
)
func main() {
printUser("poying", 21)
printUser("poying 2.0")
printUser("poying 3.0", nil)
}
func printUser(name string, options ...interface{}) {
age, _ := getOptVal(options, 0, 1).(int)
fmt.Printf("name: %s\nage: %d\n\n", name, age)
}
func getOptVal(options interface{}, index int, defVal interface{}) interface{} {
ret := defVal
s := reflect.ValueOf(options)
if s.Len() > index {
ret = s.Index(index).Interface()
}
if ret == nil {
ret = defVal
}
return ret
}
@poying
Copy link
Author

poying commented Sep 3, 2014

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