【问题标题】:What's the Go Equivalent of Java's System.arraycopy()?Java 的 System.arraycopy() 的 Go 等价物是什么?
【发布时间】:2022-01-20 06:25:56
【问题描述】:

Java 的 java.lang.System.arraycopy() 是否有任何 Golang 等效项?

arraycopy(Object source_arr, int sourcePos, Object dest_arr, int destPos, int len)

将源数组从特定的开始位置复制到目标数组中的指定位置。要复制的参数数量由len 参数决定。 source_Positionsource_Position + length – 1 的组件被复制到目标数组,从 destination_Positiondestination_Position + length – 1

【问题讨论】:

标签: java arrays go slice


【解决方案1】:

您可以使用内置的copy() 函数。

func copy(dst, src []Type) int

它只需要 2 个参数:目标切片和源切片,但您可以使用 slice expressions 指定“缺失”参数,因为 copy() 复制的元素不会超过源中可用的元素或可以放入目的地(见Why can't I duplicate a slice with `copy()`?)。

src := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
dst := make([]int, len(src))

sourcePos := 2
destPos := 3
length := 4

copy(dst[destPos:], src[sourcePos:sourcePos+length])

fmt.Println(dst)

输出(在Go Playground上试试):

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

另一种变体是将length 添加到destPos

copy(dst[destPos:destPos+length], src[sourcePos:])

【讨论】:

    猜你喜欢
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 2011-10-13
    • 2012-03-05
    相关资源
    最近更新 更多