list遍历和类型判断

package main

 import (

   "container/list"

   "fmt"

   "reflect"

 )


 type person struct {

    name string

    age  int

}

type boy struct {

    person

sex  string

}

 func main() {

   l := list.New()

   p := person{name:"tomtian", age:10000}

   b := boy{person:person{name:"tomtian", age:10000},sex:"man"}

   l.PushBack(p)

   l.PushBack(b)

   for e := l.Front(); e != nil; e = e.Next() {

fmt.Println(reflect.TypeOf(e.Value).Name())

typename := reflect.TypeOf(e.Value).Name()

if typename == "person" {

p1 := e.Value.(person)

fmt.Printf("found person: name[%s],age[%d]\n", p1.name, p1.age)

} else if typename == "boy" {

p1 := e.Value.(boy)

fmt.Printf("found boy: name[%s],age[%d] sex[%s]\n", p1.name, p1.age, p1.sex)

}

   }

 }

你可能感兴趣的:(list遍历和类型判断)