相关疑难解决方法(0)

是否可以在golang中调用父结构的重写方法?

我想实现这样的代码,其中B继承自A并且只覆盖A的Foo()方法,我希望代码打印B.Foo(),但它仍然打印A.Foo(),似乎接收器在Golang在C++中无法像这样工作,在启用动态绑定的情况下,代码可以像我想要的那样工作.

我还发布了另一段代码,但它实现起来太难了,而且更像是一种黑客方式,我认为它不是Golang风格.

所以我的问题是:如果父的Bar()方法有一些逻辑,例如,打开一个文件,然后读取一些行,并使用Foo()将这些行输出到stdout,并将Child(在示例中为B)想要使用它们中的大多数,唯一的区别是Child希望Foo()将行输出到另一个文件.我该如何实施呢?我听说Golang的继承不能像C++或Java那样工作,Golang中的正确方法是什么?

package main 

import ( 
        "fmt" 
) 

type A struct { 
} 

func (a *A) Foo() { 
        fmt.Println("A.Foo()") 
} 

func (a *A) Bar() { 
        a.Foo() 
} 

type B struct { 
        A 
} 

func (b *B) Foo() { 
        fmt.Println("B.Foo()") 
} 

func main() { 
        b := B{A: A{}} 
        b.Bar() 
}

output: A.Foo()
Run Code Online (Sandbox Code Playgroud)

以下作品有效,但写作时

a := A{}
a.Bar()
Run Code Online (Sandbox Code Playgroud)

您将遇到编译器错误

package main

import (
    "fmt"
)

type I interface {
    Foo()
}

type A struct {
    i I

}

func (a *A) …
Run Code Online (Sandbox Code Playgroud)

oop inheritance overriding go

49
推荐指数
4
解决办法
4万
查看次数

在Go中创建复杂的结构层次结构的惯用方法是什么?

我在Go写一个解释器,我正在寻找存储AST的惯用方法.我读了Go编译器源代码,似乎他们使用带有空方法的接口来表示AST.例如,我们有以下层次结构,

Object
--Immovable
----Building
----Mountain
--Movable
----Car
----Bike
Run Code Online (Sandbox Code Playgroud)

这就是上述层次结构以"空方法"的方式实现的方式.

type Object interface {
  object()
}

type Immovable interface {
  Object
  immovable()
}

type Building struct {
  ... 
}

type Mountain struct {
  ... 
}

type Movable interface {
  Object
  movable()
}

type Car struct {
  ...
} 

type Mountain struct {
  ...
} 

func (*Building) object() {}
func (*Mountain) object() {}
func (*Car) object() {}
func (*Bike) object() {}
func (*Building) immovable() {}
func (*Mountain) immovable() {}
func (*Car) movable() …
Run Code Online (Sandbox Code Playgroud)

inheritance struct interface embedding go

8
推荐指数
1
解决办法
952
查看次数

转换嵌入式struct call子方法代替父方法

这里是Go代码示例,包含Interface,Parent Struct和2 Children Structs

package main

import (
    "fmt"
    "math"
)

// Shape Interface : defines methods
type ShapeInterface interface {
    Area() float64
    GetName() string
    PrintArea()
}

// Shape Struct : standard shape with an area equal to 0.0
type Shape struct {
    name string
}

func (s *Shape) Area() float64 {
    return 0.0
}

func (s *Shape) GetName() string {
    return s.name
}

func (s *Shape) PrintArea() {
    fmt.Printf("%s : Area %v\r\n", s.name, s.Area())
}

// Rectangle Struct : …
Run Code Online (Sandbox Code Playgroud)

methods struct parent-child go

4
推荐指数
1
解决办法
848
查看次数