dtncv04228 2017-07-02 12:37
浏览 28

golang-树结构抽象

i'm trying to code a tree structure where each node should have an id and parent ref/id params.

by extending a node struct you should be able to add some custom parameters (like title, icon, color...). it should be inlined and inserted with mgo later on...

you can find the code below or here: https://play.golang.org/p/bbvs2iM3ri

i'm trying to avoid adding methods to the nodeExtension struct and sharing it through the node struct. but, the CreateNode method is getting only the node data and not the wrapping struct.

any ideas how to implement this algorithm without loosing the custom parameters (Description in this case)?

thanks

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
", 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 :/
  • 写回答

1条回答 默认 最新

  • dongyuduan1890 2017-07-02 14:35
    关注

    Your CreateNode() function operates on a type of node, which does not have a Description field. Changing the signature to: func (t *nodeExtension) CreateNode() will operate how you want it to in this scenario: it will print out the entire nodeExtension struct: https://play.golang.org/p/nLxblNySB9

    I'm not entirely sure what you're trying to accomplish here, but maybe having an interface of type node and which implements a String() method and then have like a simpleNode and extendedNode would be something you could look at?

    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图