Go类型嵌套

Go没有继承,但是有类型嵌套,主要有三种使用方式,使用类型嵌套,wrapper可以自动获得被嵌套类型的所有方法。接下来我们分别看 三种情况下的例子:

  • struct中嵌套struct

    package main
    
    import (
    	"fmt"
    )
    
    type Foo struct{}
    
    func (f Foo) SayFoo() {
    	fmt.Println("foo")
    }
    
    type Bar struct {
    	Foo
    }
    
    func main() {
    	b := Bar{}
    	b.SayFoo()
    }
    
  • interface中嵌套interface,对于接口来说,则是自动获得被嵌套的接口规定的方法,所以实现ReadWriter的实例必须同时有 ReadWrite 方法。

    type Reader interface {
    	Read(p []byte) (n int, err error)
    }
    
    type Writer interface {
    	Write(p []byte) (n int, err error)
    }
    
    type ReadWriter interface {
    	Reader
    	Writer
    }
    
  • struct中嵌套interface,这种情况比较特殊,struct中嵌套interface之后,struct会自动获得接口规定的方法:

    package main
    
    import (
    	"fmt"
    )
    
    type Foo interface {
    	SayFoo()
    }
    
    type foo struct{}
    
    func (f foo) SayFoo() {
    	fmt.Println("foo")
    }
    
    type Bar struct {
    	Foo
    }
    
    func main() {
    	b := Bar{foo{}} // 传入一个符合 Foo 这个接口的实例
    
    	b.SayFoo()
    }
    


更多文章
  • Gin源码阅读与分析
  • 如何面试-作为面试官得到的经验
  • 自己写一个容器
  • Golang(Go语言)中实现典型的fork调用
  • 软件开发之禅---大事化小,各个击破
  • 程序员的自我修养:链接,装载与库 阅读笔记
  • Redis源码阅读与分析二:双链表
  • Redis源码阅读与分析三:哈希表
  • Redis源码阅读与分析一:sds
  • Golang runtime 源码阅读与分析
  • Golang的一些坑
  • GC 垃圾回收
  • 设计一个路由
  • Go语言性能优化实战
  • 那些年开发的时候踩过的坑