美文网首页
2019-05-15

2019-05-15

作者: sujeking | 来源:发表于2019-05-15 09:30 被阅读0次

    继承

    /* 继承
    一个结构体嵌到另一个结构体,称作组合
    匿名和组合的区别
    如果一个struct嵌套了另一个匿名结构体,那么这个结构可以直接访问匿名结构体的方法,从而实现继承
    如果一个struct嵌套了另一个【有名】的结构体,那么这个模式叫做组合
    如果一个struct嵌套了多个匿名结构体,那么这个结构可以直接访问多个匿名结构体的方法,从而实现多重继承 */

    方法的继承

    type Action interface {
        FlyAction()
        RunAction()    
    }
    
    type Bird struct { //鸟继承Action
        Action
    }
    
    type Dog stuct { //狗继承Action
        Action
    }
    
    func main(){
        bird := new(Bird)
        bird.RunAction()
    }
    

    成员的继承

    type Person struct {
        Name string
        Age  int
    }
    
    type Man struct {
        Person
    }
    
    func main() {
        man := Man{Person{Name: "xiaoming"}}
        fmt.Printf("My Name is %s", man.Name)
    }
    

    相关文章

      网友评论

          本文标题:2019-05-15

          本文链接:https://www.haomeiwen.com/subject/ilyuaqtx.html