我想实现这样的代码,其中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) 我在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) 这里是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) go ×3
inheritance ×2
struct ×2
embedding ×1
interface ×1
methods ×1
oop ×1
overriding ×1
parent-child ×1