Golang struct使用内嵌实现继承

Go通过嵌入结构或使用接口支持继承。有不同的方法可以做到这一点,而且每个方法都有一些限制。不同的方式是:

  • 通过使用嵌入式结构-父结构被嵌入到子结构中。这种方法的限制是不能使用子类型。不能将子结构体传递给需要base的函数。
  • 通过使用接口-子类型是可能的,但限制是无法引用公共属性。
  • 通过使用接口+结构-这修复了上述两种方法的限制,但其中一个限制是不可能重写方法。但有一个变通办法。

在使用结构体的继承中,基结构体被嵌入到子结构体中,并且基属性和方法可以直接在子结构体上调用。看下面的代码:

package main

import "fmt"

type base struct {
    value string
}

func (b *base) say() {
    fmt.Println(b.value)
}

type child struct {
    base  //embedding
    style string
}

func check(b base) {
    b.say()
}

func main() {
    base := base{value: "somevalue"}
    child := &child{
        base:  base,
        style: "somestyle",
    }
    child.say()
    //check(child)
}

输出:
somevalue

限制:
不支持子类型。不能将子结构体传递给需要base的函数。

例如,在上面的代码中,如果你取消注释//检查(child),它会给出编译错误:“不能使用child(类型*child)作为参数检查的类型基础”。要解决这个问题,我们可以使用接口进行继承

golang迭代map几种方式
git之gitignore
标签:
ajax-loader