Golang中的多态性

huangapple go评论81阅读模式
英文:

Polymorphism in Golang

问题

这是一个简单的示例,展示了我想要的内容:

我有一个B对象,并使用A结构体中的step1函数(共同功能)。我需要重新定义B中在A内部运行的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()    
}

我该如何做呢?

// 可能是这样
func step1(a *A) {
    self.step2(a);
}
英文:

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

得分: 7

Go语言不支持多态性。你需要通过接口和函数(而不是方法)来重新构思你想要实现的功能。

所以,思考每个对象需要满足哪个接口,然后思考你需要在该接口上工作的函数。Go标准库中有很多很好的例子,比如io.Readerio.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)
}
英文:

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

huangapple
  • 本文由 发表于 2016年1月21日 03:22:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/34908695.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定