英文:
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.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)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论