英文:
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
。你也不希望有一个指向接口的指针,所以将left
和right
的类型改为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}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论