0

I have created a struct that has a list, containing references to values of the same struct type. I am new to the go language and unable to figure out a way to access the values that automatically resolve to the above struct type.Something like this in java:

 class Node{
    String value ;
    String key;
    List<Node> children = new ArrayList<Node>();
    public Node(String key, value) {
       // rest of the code follows
    }  
 }

class AccessNode {
 public static void main(String args[]) {
     Node node = new Node("key", "value");
      // The values automatically resolve to type Node.
     for(Node node : node.children) {
       // do something
     }
} 

The Node is defined as follows:

type Node struct {
   key      string
   value    string
   isword   bool
   childern *list.List // This is essentially a list of Node}

// Next two functions are a copy of implementation in list package.

func (n *Node) Init() *Node {
    n.isword = false
    n.childern = list.New()
    return n}

func New() *Node {
    return new(Node).Init()}

Now I iterate over the children and return whenever, I get a Node whose value partially matches with the string to be compared against.

func countMatchingChars(key string, node *Node) (int, *Node) {
    count := 0
    for e := node.childern.Front(); e != nil; e = e.Next() {
            // Getting error when accessing e.Value.key
            if c := MatchCount(e.Value.key, key); c > 0 {
                return c, e.Value
         }
    }}

I am getting the following error

./trie.go:53: e.Value.key undefined (type interface {} has no field or method key)
./trie.go:54: cannot use e.Value (type interface {}) as type *Node in return argument: need type assertion

1 Answer 1

0

I get the solution and along with it have discovered interfaces in go :)

if c := MatchCount(e.Value.(*Node).key, key); c > 0 {
        return c, e.Value.(*Node)
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.