内容简介: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 循环嵌套
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Django 1.0 Template Development
Scott Newman / Packt / 2008 / 24.99
Django is a high-level Python web application framework designed to support the rapid development of dynamic websites, web applications, and web services. Getting the most out of its template system a......一起来看看 《Django 1.0 Template Development》 这本书的介绍吧!