GoLang 二叉树 – 使用接口和结构体

huangapple go评论76阅读模式
英文:

GoLang Binary Tree - using Interface and Struct

问题

我正在尝试使用Go语言中的接口和结构体来创建二叉树的概念。

我编写了以下代码:

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())

}

现在,我该如何实例化左右节点(left和right)?我正在使用带有Go自动完成功能的VIM。在按下.时,没有显示列表。这意味着无法访问到s指针对象。

如何实例化和使用左右节点(left和right)?

英文:

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

得分: 1

你不需要将s声明为node,可以使用*node_element作为node。你也不希望有一个指向接口的指针,所以将leftright的类型改为node

然后你可以直接赋值字段:

s := &node_element{}
s.add(1)
s.left = &node_element{element: 2}
s.right = &node_element{element: 3}
英文:

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}

huangapple
  • 本文由 发表于 2017年1月31日 05:59:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/41946148.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定