dougan5772 2017-01-30 21:59
浏览 119
已采纳

GoLang二叉树-使用界面和结构

I am trying to use Interfaces and Struct in GoLang to create a binary tree concept

I wrote the below code

package main

import "fmt"

type node interface {
    add(a int)
    getval() int
}

type node_element struct {
    element int

    left  *node
    right *node
}

func (c *node_element) add(a int) {
    c.element = a
}

func (c *node_element) getval() int {
    return c.element
}

func main() {

    var s node

    s = &node_element{}

    s.add(1)

    fmt.Println(s.getval())

}

Now how do I instantiate left and right. I am using VIM with Go autocomplete. In auto complete on pressing . there is no list. Which means access to this pointer object to s is not happening

How to instantiate and use left and right ?

  • 写回答

1条回答 默认 最新

  • dongtuo8170 2017-01-30 22:15
    关注

    You don't need to declare s as a node, a *node_element can be used as a node. You also never want to have a pointer to an interface, so change the left and right types to node.

    You can then just assign the fields directly:

    s := &node_element{}
    s.add(1)
    s.left = &node_element{element: 2}
    s.right = &node_element{element: 3}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测