dragon4808 2017-08-02 15:44
浏览 76
已采纳

Golang多维切片副本

I was trying to make a clone of multidimensional slice, because when I was changed elements in duplicated slice, the elements in original one was overwritten also.

The only method that worked for me was:

duplicate := make([][]int, len(matrix))
for i := 0; i < len(matrix); i++ {
    duplicate[i] = make([]int, len(matrix[0]))
    for j := 0; j < len(matrix[0]); j++ {
        duplicate[i][j] = matrix[i][j]
    }
}

is there any other way - shorter or more efficient to achieve the same result? thanks

  • 写回答

1条回答 默认 最新

  • dqeq885710 2017-08-02 16:06
    关注

    You can use copy for the inner loop (which should be more efficient) and range for the outer loop (which results in nicer code).

    Result:

    duplicate := make([][]int, len(matrix))
    for i := range matrix {
        duplicate[i] = make([]int, len(matrix[i]))
        copy(duplicate[i], matrix[i])
    }
    

    If your goal is efficiency, it may make sense to do more allocation up front. This doesn't lead to more readable code but will lead to more efficient code if you are doing this often. This code assumes you have at least one row and that all rows are of the same length. You will need to add tests for that.

    n := len(matrix)
    m := len(matrix[0])
    duplicate := make([][]int, n)
    data := make([]int, n*m)
    for i := range matrix {
        start := i*m
        end := start + m
        duplicate[i] = data[start:end:end]
        copy(duplicate[i], matrix[i])
    }
    

    Depending on what you are doing, it may make sense to make a "matrix type" that is implemented using only a single slice. A slice of slices is not the most efficient data structure, even if it is simpler to work with.


    Before deciding if you need to be efficient, make sure that you are spending a lot of time doing copying using profiling. Then, after you have determined this is in fact a hotspot, start running benchmarks. See https://golang.org/pkg/testing/#hdr-Benchmarks for details.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀