dongyu2764 2014-10-17 20:42
浏览 38
已采纳

复制Go切片的通用方法?

Beginner Go programmer here. I have a need to duplicate slices (and part of the underlying array) so a caller won't mutate the original elements of an array. I think I can write a function to do this for arrays of specific types:

func duplicateSliceOfSomeType(sliceOfSomeType []SomeType) []SomeType {
    dulicate := make([]SomeType, len(sliceOfSomeType))
    copy(duplicate, sliceOfSomeType)
    return duplicate
}

But is there a way to create the same method generically, perhaps without generics?

func duplicateSlice(slice []?) []?{
    duplicate := make([]?, len(slice))
    copy(duplicate, slice)
    return duplicate
}
  • 写回答

2条回答 默认 最新

  • douwen5681 2014-10-17 20:53
    关注

    You could write one simple statement to make a shallow copy of a slice,

    b := append([]T(nil), a...)
    

    Which is equivalent to,

    b := make([]T, len(a))
    copy(b, a)
    

    For example,

    package main
    
    import "fmt"
    
    type T int
    
    func main() {
        a := []T{4, 2}
    
        b := append([]T(nil), a...)
    
        fmt.Println(&a[0], a, &b[0], b)
        b[0] = 9
        fmt.Println(&a[0], a, &b[0], b)
    }
    

    Output:

    0x10328000 [4 2] 0x10328020 [4 2]
    0x10328000 [4 2] 0x10328020 [9 2]
    

    ADDENDUM:

    Common difficulties with reflection

    If people are new to Go, they shouldn't be using reflection at all.

    -rob

    Reflection is subtle even for experts. It exposes details whose understanding depends on knowing pretty fundamental things about how the language works and, to a lesser extent, how it is implemented. It can be bewildering even for experienced Go programmers; for newly minted Gophers there are much more important, simpler things to learn first. Those who learn reflection too early confuse themselves cloud their understanding of those fundamentals. Best to keep it at arm's length until the rest of the picture is clear.

    -rob

    That said,

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    func CopySlice(s interface{}) interface{} {
        t, v := reflect.TypeOf(s), reflect.ValueOf(s)
        c := reflect.MakeSlice(t, v.Len(), v.Len())
        reflect.Copy(c, v)
        return c.Interface()
    }
    
    type T int
    
    func main() {
    
        {
            // append
            a := []T{4, 2}
            b := append([]T(nil), a...)
            fmt.Println(&a[0], a, &b[0], b)
            b[0] = 9
            fmt.Println(&a[0], a, &b[0], b)
        }
    
        {
            // make and copy
            a := []T{4, 2}
            b := make([]T, len(a))
            copy(b, a)
            fmt.Println(&a[0], a, &b[0], b)
            b[0] = 9
            fmt.Println(&a[0], a, &b[0], b)
        }
    
        {
            // reflection
            a := []T{4, 2}
            b := CopySlice(a).([]T)
            fmt.Println(&a[0], a, &b[0], b)
            b[0] = 9
            fmt.Println(&a[0], a, &b[0], b)
        }
    
    }
    

    Output:

    0xc20800a200 [4 2] 0xc20800a210 [4 2]
    0xc20800a200 [4 2] 0xc20800a210 [9 2]
    0xc20800a290 [4 2] 0xc20800a2a0 [4 2]
    0xc20800a290 [4 2] 0xc20800a2a0 [9 2]
    0xc20800a310 [4 2] 0xc20800a320 [4 2]
    0xc20800a310 [4 2] 0xc20800a320 [9 2]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗