I want to implement a graph data structure, where each node is represented by:
type Node struct {
root string
links []*Node
}
Basically each node has a value root and a list of links, for each link a only want to store a pointer to it, since the memory of the struct will be allocated and owned by a map:
rooturl := "root"
graph := Node{rooturl, []*Node{}}
graphMap := make(map[string]Node)
graphMap[rooturl] = graph
The problem comes when I try to append a pointer to a newly created Node:
u := "new node"
// if the link is not stored in the graph not create a new node
if _, exists := graphMap[u]; !exists {
graphMap[u] = Node{u, []*Node{}}
}
// add the links to the graph
graphMap[rooturl].links = append(graphMap[rooturl].links, &graphMap[u])
I get two errors:
cannot assign to struct field graphMap[rooturl].links in map
and
cannot take the address of graphMap[u]
How should I solve this properly?
I would also like the need to query the map twice with graphMap[rooturl].links when appending (but since I cannot take a pointer or a reference to it I don't know how)