dongzhentiao2326 2013-09-01 15:19
浏览 509
已采纳

用Go语言复制数组的功能

Is there any built-in function in Go for copying one array to another? Will this work in case of two (or more) dimensional arrays?

  • 写回答

3条回答 默认 最新

  • dryb38654 2013-09-01 15:41
    关注

    Is there any built-in function in Go language for copying one array to another?

    Yes: http://play.golang.org/p/_lYNw9SXN5

    a := []string{
        "hello",
        "world",
    }
    b := []string{
        "goodbye",
        "world",
    }
    
    copy(a, b)
    
    // a == []string{"goodbye", "world"}
    

    Will this work in case of two (or more) dimensional arrays?

    copy will do a shallow copy of the rows: http://play.golang.org/p/0gPk6P1VWh

    a := make([][]string, 10)
    
    b := make([][]string, 10)
    for i := range b {
        b[i] = make([]string, 10)
        for j := range b[i] {
            b[i][j] = strconv.Itoa(i + j)
        }
    }
    
    copy(a, b)
    
    // a and b look the same
    
    b[1] = []string{"some", "new", "data"}
    
    // b's second row is different; a still looks the same
    
    b[0][0] = "apple"
    
    // now a looks different
    

    I don't think there's a built-in for doing deep-copys of multi-dimensional arrays: you can do it manually like: http://play.golang.org/p/nlVJq-ehzC

    a := make([][]string, 10)
    
    b := make([][]string, 10)
    for i := range b {
        b[i] = make([]string, 10)
        for j := range b[i] {
            b[i][j] = strconv.Itoa(i + j)
        }
    }
    
    // manual deep copy
    for i := range b {
        a[i] = make([]string, len(b[i]))
        copy(a[i], b[i])
    }
    
    b[0][0] = "apple"
    
    // a still looks the same
    

    edit: As pointed out in the comments, I assumed by "copy an array" you meant "do a deep copy of a slice", as arrays can be deep-copied with the = operator as per jnml's answer (because arrays are value types): http://play.golang.org/p/8EuFqXnqPB

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路