I came across a problem which needed editing several indexes of a 2-dimensional slice.
Imagine the following numbers as a 2-d slice of slices a [][]int
0 1 2 3
1 2 3 4
2 3 4 5
3 4 5 6
The problem is that I want to access and modify
0 1
1 2
As a sub-slice and I want a to be changed as well. I achieved that with this code :
sub := a[:2]
for i := range sub {
sub[i] = sub[i][:2]
}
Now fmt.Println(sub)
prints [[0 1] [1 2]]
But the problem is fmt.Println(a)
is printing [[0 1] [1 2] [2 3 4 5] [3 4 5 6]]
The question is, how can I access this sub-slice without losing any data?
If your goal to modify the original []int slice elements when using sub
, then copy the elements of a
to a new slice. The code in the question modifies a
directly.
sub := make([][]int, 2)
for i := range sub {
sub[i] = a[i][:2]
}
Just found a solution but don't know if it's the right way of doing so
sub := make([][]int, 2)
for i := range sub {
sub[i] = a[i][:2]
}
sub[0][0] = "876"
fmt.Println(a)
fmt.Println(sub)
now in the output I have
[[876 1 2 3] [1 2 3 4] [2 3 4 5] [3 4 5 6]]
[[876 1] [1 2]]