dongyan3237 2016-01-20 19:22
浏览 120
已采纳

Golang中的多态性

It's simple example what I want:

I have object of B and use function step1 from struct A (common functionality). I need to redefine function step2 for B which runs inside A.

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() 
}

How can I do it?

// maybe 
func step1(a *A) {
   self.step2(a);
}
  • 写回答

1条回答 默认 最新

  • dounai7148 2016-01-20 20:26
    关注

    Go doesn't do polymorphism. You have to recast what you want to do in terms of interfaces, and functions (not methods) that take those interfaces.

    So think what interface does each object need to satisfy, then what functions you need to work on that interface. There are lots of great examples in the go standard library, eg io.Reader, io.Writer and the functions which work on those, eg io.Copy.

    Here is my attempt to recast your example into that style. It doesn't make a lot of sense, but hopefully it will give you something to work on.

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制