Created
September 3, 2014 23:53
-
-
Save poying/df50195b71350e233d40 to your computer and use it in GitHub Desktop.
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" | |
"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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://play.golang.org/p/8IiNcjem9u