pointers - 调用结构属性方法时 Golang 结构指针引用丢失

标签 pointers go struct

我正在尝试使用 struct 来管理树上的访问节点。每当我访问父节点的子节点的方法时,后续调用的父引用就会丢失(即 parent.child.method(child) -> [parent becomes nil]-> parent(the previous child).child ...等等).

这是我文件中的错误片段。

type Node struct {
    Left *Node
    Right *Node
    value int
}

func (parent *Node) determineSide(child *Node) (Node, Node) {

    if child.Value < parent.Value {
        if parent.hasLeftNode() {
            return parent.Left.determineSide(child)
        }
        return parent.addLeftNode(child)

    } else if child.Value > parent.Value {
        if parent.hasRightNode() {
           return parent.Right.determineSide(child)
        }
        return parent.addRightNode(child)
    }
    return *child, *parent
 }

我试图通过尝试找到一种方法来通知方法新引用应该是 parent.Left 来解决这个问题。使用 *parent.Left&parent.Left 之类的东西似乎不正确。

一个解决方案可能是将此代码移到 struct 之外,并让另一个函数处理结果以快速修复,但我想了解为什么这不起作用盒子。这里的思维过程受到使用 this.child.determineSide(child) 的影响。

完整代码是 here .

编辑

这是终端的一些输出,可能会提供更多上下文。看起来我遇到了导致问题的支票类型问题。

parent &{<nil> <nil> 2}
parent.Left <nil>
parent.LeftNode true
child &{<nil> <nil> 1}
parent <nil>
child &{<nil> <nil> 1}

最佳答案

好吧,我终于知道你到底在问什么了。

New()方法返回一个值,而不是指针,这意味着您看不到调用者以后的更改。调用者得到的只是 Node.js 的一个值副本。所以你打印的父级永远是{Left:<nil> Right:<nil> Value:2} .

addLeftNode() 相同和 addRightNode() .

只需使用指针,而不是值来实现您的目标。

参见 pointers_vs_values


我认为它只是 Visit()问题所在的方法。

  1. 当你访问完左 child 后立即返回时,它永远不会访问右 child 。
  2. 左右 child 不互斥,所以第二个if子句不应该使用else if ,这将是 if .
  3. 访问顺序也有问题。

之前:

// Visit will automatically walk through the Child Nodes of the accessed Parent Node.
func (parent *Node) Visit() (Node, int) {
    fmt.Println("Node value:", parent.Value)
    if parent.hasLeftNode() {
        return parent.Left.Visit()
    } else if parent.hasRightNode() {
        return parent.Right.Visit()
    }
    return *parent, parent.Value
}

修改:

// Visit will automatically walk through the Child Nodes of the accessed Parent Node.
func (parent *Node) Visit() (Node, int) {
    if parent.hasLeftNode() {
        parent.Left.Visit()
    }
    fmt.Println("Node value:", parent.Value)
    if parent.hasRightNode() {
        parent.Right.Visit()
    }
    return *parent, parent.Value
}

此外,对于我来说,Visit()不应返回任何值。

关于pointers - 调用结构属性方法时 Golang 结构指针引用丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53967792/

相关文章:

C 结构指针问题

c - 什么时候传递一个指向结构的指针作为参数,什么时候传递一个指向结构指针的指针?

c# - 将 C++ 指针数学转换为 C#

mongodb - go mongodb FindOneAndUpdate 几个字段

c++ - 如何拥有带有类模板的结构

c++ - 为什么此 C++ 成员函数调用会因段错误而失败?

c - 指向字节数组的指针

go - 从环境中获取变量?

go - 在 golang 中捕获 stdErr 输出

c - 在函数中传递结构成员