Golang的多态性

Har*_*lam 1 oop polymorphism go

这是我想要的简单例子:

我有B的对象并使用struct A中的函数step1(常用功能).我需要重新定义在A内部运行的B的函数step2.

package main

import "fmt"

type A struct {}

func (a *A) step1() {
    a.step2();
}

func (a *A) step2 () {
   fmt.Println("get A");
}


type B struct {
   A
}

func (b *B) step2 () {
   fmt.Println("get B");
}

func main() {
    obj := B{}
    obj.step1() 
}
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

// maybe 
func step1(a *A) {
   self.step2(a);
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*ood 6

Go不做多态.您必须根据接口以及采用这些接口的函数(而不是方法)重新制作您想要做的事情.

因此,请考虑每个对象需要满足哪个接口,然后在该接口上使用哪些函数.go标准库中有很多很好的例子,例如io.Reader,io.Writer那些工作的函数,例如io.Copy.

这是我尝试将你的例子改造成那种风格的尝试.它没有多大意义,但希望它会给你一些工作.

package main

import "fmt"

type A struct {
}

type steps interface {
    step1()
    step2()
}

func (a *A) step1() {
    fmt.Println("step1 A")
}

func (a *A) step2() {
    fmt.Println("get A")
}

type B struct {
    A
}

func (b *B) step2() {
    fmt.Println("get B")
}

func step1(f steps) {
    f.step1()
    f.step2()
}

func main() {
    obj := B{}
    step1(&obj)
}
Run Code Online (Sandbox Code Playgroud)