Golang slice iteration in another function call

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 Tour of Go

Range

The range form of the for loop iterates over a slice or map.

When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.


The Go Programming Language Specification:

For statements

For statements with range clause

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.

You could also do this:

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
       }  
    }
}
1 Like

From the question:

which seems to imply

func funcToGetNodeId(node node.Node) int

which would likely change your solution to

node := &path[i]
ndId := funcToGetNodeId(*node)
2 Likes

true

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.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.