【问题标题】:golang - tree structure abstractiongolang - 树结构抽象
【发布时间】:2017-12-05 20:33:28
【问题描述】:

我正在尝试编写一个树结构,其中每个节点都应该有一个 id 和父 ref/id 参数。

通过扩展节点结构,您应该能够添加一些自定义参数(如标题、图标、颜色...)。以后应该用mgo内联和插入...

您可以在下面或此处找到代码:https://play.golang.org/p/bbvs2iM3ri

我试图避免向 nodeExtension 结构添加方法并通过 node 结构共享它。但是,CreateNode 方法只获取节点数据而不是包装结构。

任何想法如何在不丢失自定义参数的情况下实现此算法(在这种情况下为描述)?

谢谢

package main

import (
    "fmt"
)

type item struct {
    ID string
}

type node struct {
    item   `bson:,inline`
    Parent string
}

func (t *node) CreateNode() {
    fmt.Printf("Node: %+v\n", t)
}

type nodeExtension struct {
    node        `bson:,inline`
    Description string
}

func main() {
    i := &nodeExtension{
        node: node{
            item: item{
                ID: "1",
            },
            Parent: "",
        },
        Description: "Root node",
    }
    i.CreateNode()

    i = &nodeExtension{
        node: node{
            item: item{
                ID: "2",
            },
            Parent: "1",
        },
        Description: "Another node",
    }
    i.CreateNode()
}


// output:
// Node: &{item:{ID:1} Parent:}
// Node: &{item:{ID:2} Parent:1}

// both without description :/

【问题讨论】:

    标签: oop go


    【解决方案1】:

    您的CreateNode() 函数在node 类型上运行,该类型没有Description 字段。 将签名更改为: func (t *nodeExtension) CreateNode() 在这种情况下将按照您希望的方式运行:它将打印出整个 nodeExtension 结构: https://play.golang.org/p/nLxblNySB9

    我不完全确定您要在这里完成什么,但可能有一个node 类型的接口,它实现了一个String() 方法,然后有一个simpleNode 和extendedNode 将是有什么可以看的吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-03
      • 2019-08-20
      相关资源
      最近更新 更多