S
S
Sergei Abramov2020-09-16 13:18:24
go
Sergei Abramov, 2020-09-16 13:18:24

How to change two dimensional array in for?

I'm trying to change a two-dimensional array - add a value. But since everything is passed by value, naturally I can’t do this. Tried to write something like this:

for _, *innerArray := range &arr {
    innerArray = append(innerArray, "ddddd")
}

But you can't do that)) How to correctly add a value to a nested array? Example code:

package main

import "fmt"

func main() {
  var arr = [][]string{{"el1"}, {"el1", "el2"}, {}}

  for _, innerArray := range arr {
    fmt.Printf("len: %d\n", len(innerArray))
  }

  fmt.Println("----------")

  for _, innerArray := range arr {
    innerArray = append(innerArray, "ddddd")
  }

  for _, innerArray := range arr {
    fmt.Printf("len: %d\n", len(innerArray))
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WinPooh32, 2020-09-16
@PatriotSY

....  
 for i, _ := range arr {
    arr[i] = append(arr[i], "ddddd")
  }
....

In your case, innerArray is a slice that contains a pointer to an array inside, but when you do append and size goes beyond capacity, a new array is allocated and a new value is added to it.
In addition, innerArray is a local variable in the form of a slice, which is only accessible within the loop.
By assigning a new value to it from append() you do not change the value of the slice variable in the array, and the new slice from append already points to another array with the added element.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question