请教一个 Golang Go语言 struct 的问题

type Parent struct{}

func (p *Parent) A() { p.B() }

func (p *Parent) B() { fmt.Println(“parent.B()”) }

type Child struct { Parent }

func (c *Child) B() { fmt.Println(“child.B()”) }

定义了两个结构体,Parent 和 Child
Parent 有 A()和 B()两个方法,在 A 中调用了 B
Child 只实现了 B(),然后按如下方式调用:

func main() {
	p := &Parent{}
	c := &Child{}
	p.A()
	c.A()
	c.Parent.A()
}

发现 c.A()和 c.Parent.A()都只调用到了 Parent 的 B()方法
有办法可以在 A()方法中调用到 Child 的 B()方法吗


请教一个 Golang Go语言 struct 的问题

更多关于请教一个 Golang Go语言 struct 的问题的实战教程也可以访问 https://www.itying.com/category-94-b0.html

16 回复

不可能吧?!

更多关于请教一个 Golang Go语言 struct 的问题的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


go 的嵌套不会重载,所以都是ParentB()方法。

使用interface可以解决你的需求。

加一个方法

func (c *Child) A() {
c.B()
}

调什么方法得看方法绑定的指针类型

Golang 中 Parent 不知道 Child 的存在,一旦调用了 Parent 的方法,之后所有的调用都局限在 Parent 中。

其实可以解释的更简单一点:Golang 没有 Override。之所以 c.A()能运行,仅仅是因为这是一种语法糖。实际上 c.A()跟 c.Parent.A()是等价的。

楼上已经回答的很清楚了。
不过即使是在支持重载的语言中这个写法也不怎么优雅吧?

你需要 interface

还有种方法

package main

import "fmt"

type CanB interface {
B()
}

type Parent struct {
instance CanB
}

func (p *Parent) A() {
p.B()
}

func (p *Parent) B() {
if p.instance != nil {
p.instance.B()
return
}
fmt.Println(“parent.B()”)
}
func (p *Parent) SetInstance(i interface{}) {
if inst, ok := i.(CanB); ok {
p.instance = inst
}
}

type Child struct {
Parent
}

func (c *Child) B() {
fmt.Println(“child.B()”)
}

func main() {
p := &Parent{}
c := &Child{}

c.SetInstance©

p.A()
c.A()
c.Parent.A()
}

重载 Child 的 A 方法
chlid.A()会调用到 child 的 A 方法
child.parent.A()会调用到 parent 的 A 方法

个人觉得,go 没有 oop ……

所谓的继承其实就是帮你自动调用嵌入结构的同名函数的语法糖。

就我的角度来看,大部分的操作 需要一个外部函数 调用 interface 来处理。

而非写作方法本身。

也就是 不是 p.A(),c.A()
而是 A§,A©

2L 正解 贴下实现,顺便贴下实现(不是很喜欢这么写),https://play.golang.org/p/6NcQ45ai8v

其实原理和你说的是基本一样的 p.A()和 A§ 记得 go 笔记那本书里有写

厉害了

学习了楼上给出的方法,非常感谢

当然,我很乐意帮你解答关于 Go 语言中 struct 的问题。

在 Go 语言中,struct 是一种自定义的数据类型,它允许你将零个或多个任意类型的字段组合在一起。struct 在定义和使用时非常灵活,是 Go 语言编程中非常重要的一部分。

关于 struct 的一些关键点包括:

  1. 定义:你可以使用 type 关键字来定义一个 struct 类型,并在花括号 {} 中列出它的字段。例如:

    type Person struct {
        Name string
        Age  int
    }
    
  2. 实例化:你可以使用字面量语法来创建一个 struct 的实例,并初始化它的字段。例如:

    p := Person{Name: "Alice", Age: 30}
    
  3. 访问和修改字段:你可以通过点操作符 . 来访问或修改 struct 的字段。例如:

    fmt.Println(p.Name) // 输出: Alice
    p.Age = 31
    
  4. 嵌套 struct:一个 struct 的字段可以是另一个 struct 类型,这样可以实现更复杂的数据结构。

  5. 方法接收者:你可以为 struct 定义方法,方法接收者可以是值接收者或指针接收者。

如果你有更具体的问题,比如关于 struct 的内存布局、嵌套 struct 的使用场景,或者如何为 struct 定义方法,请提供更多细节,我将更针对性地为你解答。

回到顶部