wangming1993 / issues

记录学习中的一些问题,体会与心得 https://wangming1993.github.io/issues
8 stars 4 forks source link

golang中组合继承,接口实现 #38

Open wangming1993 opened 8 years ago

wangming1993 commented 8 years ago
type Namer struct {
    Name string
}

func (this *Namer) Length() int {
    fmt.Println("will return name lenght...")
    return len(this.Name)
}

type IName interface {
    Length() int
}

func main() {
    //var name *Namer = &Namer{"mike"}
    //iname := reflect.ValueOf(name).Interface().(IName)
    //fmt.Println(iname.Length())
    nameType := reflect.TypeOf(&Namer{})
    v := reflect.New(nameType).Elem().Interface()
        // 这里只是new了一个空的Namer出来  (*main.Namer)(nil) 
    if iname, ok := v.(IName); ok {
        fmt.Println("Name convert to Iname")
        fmt.Printf("iname:%#v \n", iname)   //iname:(*main.Namer)(nil) 
        //fmt.Println(iname.Length())   
    }

    var iname IName = &Namer{"mike"}
    fmt.Println(iname.Length())

    name := iname.(*Namer)
    fmt.Printf("iname:%#v, name:%v", name, name) 
}

type MaiError interface {
    Code() string
    Status() int
    Error() string
    Decode(desc string) MaiError
}

type BaseError struct {
    //MaiError   //也可以内嵌interface
    code   string
    status int
}

type Invaild struct {
    *BaseError
    Data map[string]interface{}
}