Calling child method from parent implementation method in golang

I am trying to implement a behavior tree in go, and I am struggling with its composite functions. Basically, I need Tick()implemented below to call a method defined by where it was built in.

Here behavior.go:

type IBehavior interface {
  Tick() Status
  Update() Status
}

type Behavior struct {
  Status Status
}

func (n *Behavior) Tick() Status {
  fmt.Println("ticking!")
  if n.Status != RUNNING { n.Initialize() }
  status := n.Update()
  if n.Status != RUNNING { n.Terminate(status) }

  return status
}

func (n *Behavior) Update() Status {
  fmt.Println("This update is being called")
  return n.Status
}

And here is the structure built in Behavior:

type IBehaviorTree interface {
  IBehavior
}

type BehaviorTree struct {
  Behavior

  Root IBehavior
}

func (n *BehaviorTree) Update() Status {
  fmt.Printf("Tree tick! %#v\n", n.Root)
  return n.Root.Tick()
}

A few examples to make this example make sense:

type ILeaf interface {
  IBehavior
}

type Leaf struct {
  Behavior
}

And this one:

type Test struct {
  Leaf

  Status Status
}

func NewTest() *Test {
    return &Test{}
}

func (n Test) Update() Status {
    fmt.Println("Testing!")
    return SUCCESS
}

And here is an example of its use:

tree := ai.NewBehaviorTree()
test := ai.NewTest()
tree.Root = test

tree.Tick()

I was expecting the tree to point normally by typing this:

ticking!
Tree tick!

But instead, I get:

ticking!
This update is being called

Can someone help me with this problem?

Edit: A few additional files have been added to highlight the problem. Also, I don't understand downvotes. I have an honest question. I only have to ask questions that make sense to me already?

+4
2

, Tick() BehaviorTree. tree.Tick() , Tick() Behavior. Behavior , BehaviorTree! Gos "" "", . , .

, Tick() BehaviorTree Update() ( sub Tick() Update() , ). :

type BehaviorTree struct {
  Behavior

  Root IBehavior
}

func (n *BehaviorTree) Tick() Status {
    n.Update() // TODO: do you want this status or the Root.Tick() status?
    return n.Root.Tick()
}

func (n *BehaviorTree) Update() Status {
  fmt.Printf("Tree tick! %#v\n", n.Root)
  return nil
}
+2

Go ( ), / Go.

, , , .

func Tick(n IBehavior) Status {
  fmt.Println("ticking!")
  if n.Status != RUNNING { n.Initialize() }
  status := n.Update()
  if n.Status != RUNNING { n.Terminate(status) }
  return status
}

, .

0

Source: https://habr.com/ru/post/1690572/


All Articles