内容简介:Go没有继承,但是有类型嵌套,主要有三种使用方式,使用类型嵌套,wrapper可以自动获得被嵌套类型的所有方法。接下来我们分别看 三种情况下的例子:
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()
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- Elasticsearch 嵌套类型nested
- go语言嵌套类型的使用细节
- ElasticSearch-Nested嵌套类型解密
- Elasticsearch 7.x Nested 嵌套类型查询 | ES 干货
- Elasticsearch 7.x Nested 嵌套类型查询 | ES 干货
- Python 循环嵌套
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
数据结构与算法分析
维斯 / 冯舜玺 / 机械工业出版社 / 2004-1-1 / 35.00元
本书是《Data Structures and Algorithm Analysis in C》一书第2版的简体中译本。原书曾被评为20世纪顶尖的30部计算机著作之一,作者Mark Allen Weiss在数据结构和算法分析方面卓有建树,他的数据结构和算法分析的著作尤其畅销,并受到广泛好评.已被世界500余所大学用作教材。 在本书中,作者更加精炼并强化了他对算法和数据结构方面创新的处理方法。......一起来看看 《数据结构与算法分析》 这本书的介绍吧!
HEX CMYK 转换工具
HEX CMYK 互转工具
HSV CMYK 转换工具
HSV CMYK互换工具