duanji1026 2018-01-30 12:49
浏览 75

Go中的Java Arrays.copyOfRange等效于什么?

I'm working on the creating a Java library that deals with management of Arrays. Is there an equivalent of Arrays.copyOfRange in Go?

  • 写回答

1条回答 默认 最新

  • doz22551 2018-01-30 12:54
    关注

    A simple one-liner would be (index check omitted):

    func copyOfRange(src []byte, from, to int) []byte {
        return append([]byte(nil), src[from:to]...)
    }
    

    A simple slice expression "almost" does the job, but since Java's Arrays.copyOfRange() returns a copy independent from the source, we need to copy the slicing result to a new slice (because the result of slicing will share the backing array).

    We can do that by allocating one with make(), and use the builtin copy(), or simply use append() to append it to an empty or nil slice, which will take care of the allocation and copying.

    Example using the above function:

    src := []byte{0, 1, 2, 3, 4, 5}
    dst := copyOfRange(src, 2, 4)
    fmt.Println(dst)
    

    Output (try it on the Go Playground):

    [2 3]
    

    For completeness, this is how it would look like with make() and copy():

    func copyOfRange2(src []byte, from, to int) []byte {
        src = src[from:to]
        dst := make([]byte, len(src))
        copy(dst, src)
        return dst
    }
    

    One thing to note here: the builtin append() allocates more space than needed, thinking of future growth. So if you don't plan to "grow" the returned slice, copyOfRange2() is a better option.

    See this comparison:

    dst := copyOfRange(src, 2, 4)
    fmt.Println(dst, cap(dst))
    
    dst = copyOfRange2(src, 2, 4)
    fmt.Println(dst, cap(dst))
    

    Output (try it on the Go Playground):

    [2 3] 8
    [2 3] 2
    

    As you can see, append() (inside copyOfRange()) allocated a backing array with a size of 8, while in our copyOfRange2() we explicitly allocated a slice (and backing array) of size 2.

    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP