Hi all, I’m new to Golang and have written this below function but the changes are not reflecting, I know it’s because paths is passed by value but when I’m passing by reference, then I’m unable to iterate over that slice. How can I do this?
func addNodeIdsToPaths(paths [][]node.Node) {
for _, path := range paths {
for _, node := range path {
ndId = funcToGetNodeId(node)
// this below change should reflect outside of this function scope
node.NodeId = ndId
}
}
}
It is hard to be precise since you have not posted key parts of your code.
You are updating the local range iteration variable node.
node.NodeId = ndId
You also need to update the slice element.
node.NodeId = ndId
paths[i][j] = node
Something like this:
for i, path := range paths {
for j, node := range path {
ndId := funcToGetNodeId(node)
// this below change should reflect outside of this function scope
node.NodeId = ndId
paths[i][j] = node
}
}
A “for” statement with a “range” clause iterates through all entries of a slice. For each entry it assigns iteration values to corresponding iteration variables if present and then executes the block.
func addNodeIdsToPaths(paths [][]node.Node) {
for _, path := range paths {
for i := range path {
node := &path[i]
ndId = funcToGetNodeId(node)
// this below change should reflect outside of this function scope
node.NodeId = ndId
}
}
}
Hi @petrus and @skillian , thanks for helping me out. Sorry for not giving complete function signatures and replying super late. I had just started with go when I posted this.
This was the function signature for funcToGetNodeId function.
func funcToGetNodeId(node node.Node) uint64
And yes, you guys are right, I should’ve used node := &path[i] to reflect the changes in node object.