douyan7916 2019-02-03 21:33
浏览 37
已采纳

使用go中的范围选择2D切片的2D子切片

I'm getting a surprising result when selecting a 2D sub-slice of a slice. Consider the following 2D int array

a := [][]int{
    {0, 1, 2, 3},
    {1, 2, 3, 4},
    {2, 3, 4, 5},
    {3, 4, 5, 6},
}

To select the top left 3x3 2D slice using ranges I would use

b := a[0:2][0:2]

I would expect the result to be

[[0 1 2] [1 2 3] [2 3 4]]

however the second index range doesn't seem to have any effect, and returns the following instead:

[[0 1 2 3] [1 2 3 4] [2 3 4 5]]

What am I missing? Can you simply not select a sub-slice like this where the dimension > 1 ?

  • 写回答

1条回答 默认 最新

  • ds20021205 2019-02-03 22:14
    关注

    You can't do what you want in a single step. Slices and arrays are not 2-dimensional, they are just composed to form a multi-dimensional object. See How is two dimensional array's memory representation

    So with a slice expression, you just get a slice that will hold a subset of the "full" rows, and its type will be the same: [][]int. If you slice it again, you just slicing the slice of rows again.

    Also note that the higher index in a slice expression is exclusive, so a[0:2] will only have 2 rows, so you should use a[0:3] or simply a[:3] instead.

    To get what you want, you have to slice the rows individually like this:

    b := a[0:3]
    for i := range b {
        b[i] = b[i][0:3]
    }
    fmt.Println(b)
    

    This will output (try it on the Go Playground):

    [[0 1 2] [1 2 3] [2 3 4]]
    

    Or shorter:

    b := a[:3]
    for i, bi := range b {
        b[i] = bi[:3]
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?