gpt4 book ai didi

go - 在不丢失接收器类型信息的情况下调用嵌入式结构接口(interface)方法

转载 作者:IT王子 更新时间:2023-10-29 02:29:20 25 4
gpt4 key购买 nike

下面的代码失败了,因为在使用了B.Assign(A)之后,B具体类型的信息丢失了(至少我是这么认为的)这里错了):

package main

import "fmt"

type Methods interface {
Method()
Assign(Methods)
Set(Methods)
}

type Parent struct {
Methods
assigned Methods
}

type ChildA struct {
Parent
}

type ChildB struct {
Parent
msg string
}

func (this *Parent) Assign(other Methods) {
//Some other logic here
other.Set(this)
}

func (this *Parent) Set(other Methods) {
this.assigned = other
}

func (c *ChildA) Method() {
fmt.Println("I'm child A")
}

func (c *ChildB) Method() {
fmt.Println("I'm child B, and I approve this message:", c.msg)
}

func main() {
A := new(ChildA)
B := new(ChildB)
B.msg = "my message"

B.Assign(A)
A.assigned.Method()

}

现在,为了避免这种情况,我必须创建另一种方法,它与 Parent.Assign() 具有完全相同的定义,但接收者不同:

func (this *Parent) Assign(other Methods) {
//Some other logic here
other.Set(this)
}

func (this *ChildB) Assign(other Methods) {
//Same as above
other.Set(this)
}

这很丑陋。有没有办法在从 B 的嵌入式结构 Parent 调用方法时保留有关 B 类型的信息,而不复制代码?

最佳答案

Is there a way to preserve the information about B's type when calling the method from it's embedded struct Parent, without duplicating the code?

没有。当您调用嵌入式方法时,它会通过指向嵌入式结构的指针进行调用。

不幸的是,嵌入式对象并没有使 Go 成为面向对象的语言,尽管它乍看起来很有吸引力。

您最好只使用一种带有用于实现的函数指针的类型。

关于go - 在不丢失接收器类型信息的情况下调用嵌入式结构接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43739330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com