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 ?
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}