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的实例必须同时有
Read
和Write
方法。
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()
}

关注公众号,获得及时更新
更多文章
本站热门
- socks5 协议详解
- 搞定面试中的系统设计题
- zerotier简明教程
- Docker组件介绍(一):runc和containerd
- Docker组件介绍(二):shim, docker-init和docker-proxy
- Golang(Go语言)中实现典型的fork调用
- Go Module 简明教程
- DNSCrypt简明教程
- frp 源码阅读与分析(一):流程和概念
- SQLAlchemy简明教程
- 协程(coroutine)简介 - 什么是协程?
- Golang validator使用教程
- 使用Go语言实现一个异步任务框架
- Golang的template(模板引擎)简明教程
- 使用Gitea+Drone打造自己的CI/CD系统