转载:http://blog.csdn.net/chdhust/article/details/51436882
面给出一个例子:
- packagemain
- import(
- "errors"
- "fmt"
- )
- typeitemstruct{
- Namestring
- }
- func(iitem)String()string{
- returnfmt.Sprintf("itemname:%v",i.Name)
- typepersonstruct{
- Sexstring
- }
- func(pperson)String()string{
- returnfmt.Sprintf("personname:%vsex:%v",p.Name,p.Sex)
- funcParse(iinterface{})interface{}{
- switchi.(type){
- casestring:
- return&item{
- Name:i.(string),
- case[]string:
- data:=i.([]string)
- length:=len(data)
- iflength==2{
- return&person{
- Name:data[0],
- Sex:data[1],
- }else{
- returnnil
- default:
- panic(errors.New("typematchmiss"))
- returnnil
- funcmain(){
- p1:=Parse("Apple").(*item)
- fmt.Println(p1)
- p2:=Parse([]string{"zhangsan","man"}).(*person)
- fmt.Println(p2)
- }
输出结果:
copy