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()
    }
    


更多文章
  • ArchLinux 怎么降级 package ?
  • Vim打开很慢,怎么找出最慢的插件?怎么解决?
  • 为什么我选择放弃运营微信公众号?
  • Web后端工程师进阶指南(2018)
  • How to implement fork syscall in Golang?
  • macOS ansible 遇到 rsync: --chown=www-data: unknown option
  • 关于运营的思考-运营要怎么做?
  • Python中实现单例模式的n种方式和原理
  • Golang defer中修改返回值
  • Python dataclass 源码阅读与分析
  • gRPC-gateway 源码阅读与分析
  • 如何阅读源代码
  • 我心目中的配置中心应该怎么做?
  • 设计一个HTTP网关
  • 设计一个分布式块存储