Go类型嵌套

栏目: Go · 发布时间: 7年前

内容简介: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的实例必须同时有 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()
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Django 1.0 Template Development

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》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具