小编Har*_*lam的帖子

Golang的多态性

这是我想要的简单例子:

我有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)

oop polymorphism go

1
推荐指数
1
解决办法
1062
查看次数

标签 统计

go ×1

oop ×1

polymorphism ×1