download1214 2019-08-16 16:09
浏览 133
已采纳

重新切片二维切片

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?

  • 写回答

2条回答 默认 最新

  • doukan6564 2019-08-16 16:24
    关注

    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]
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀