Home > Article > Backend Development > How does the Go `copy` function work with overlapping slices?
The Go programming language provides a built-in copy function that facilitates the copying of elements from one slice to another. As per the documentation, copy operates by copying elements from a source slice into a destination slice. Notably, if the destination is a slice of bytes, the source can be a string.
The signature of the copy function is as follows:
<code class="go">func copy(dst, src []Type) int</code>
where dst and src represent the destination and source slices, respectively. The return value is an integer indicating the number of elements copied, which is the minimum of the lengths of both slices.
To illustrate how copy works, consider the following example:
<code class="go">src := []int{10, 11, 12, 13, 14} dst := []int{0, 1, 2, 3, 4} n := copy(dst, src) fmt.Println("n =", n, "src =", src, "dst =", dst)</code>
Output:
n = 5 src = [10 11 12 13 14] dst = [10 11 12 13 14]
In this example, all five elements of the source slice were copied into the destination slice, resulting in the destination slice having the same elements as the source slice.
An interesting feature of copy is that it can handle overlapping slices. Overlapping refers to the scenario where the destination and source slices share the same underlying array. Even in such cases, copy functions correctly, as demonstrated in the following example:
<code class="go">copy(src, src[1:]) fmt.Println("n =", n, "src =", src)</code>
Output:
n = 4 src = [1 2 3 4 4]
In this example, src[1:] is used as the source, excluding the first element. Since the source has four elements, four elements were copied, resulting in the elements being shifted by one index.
The copy function also allows for copying bytes from a string to a slice of bytes. The following code demonstrates this:
<code class="go">str := "Hello, World!" data := make([]byte, 5) n = copy(data, str) fmt.Println("n =", n, "str =", str, "data =", data) fmt.Printf("data as string: %s\n", data)</code>
Output:
n = 5 str = Hello, World! data = [72 101 108 108 111] data as string: Hello
The copy function is a useful tool in Go for copying elements between slices. It handles both regular and overlapping slices, and even allows for copying bytes from strings to slices of bytes. Understanding the function's behavior is essential for effective slice manipulation in Go programs.
The above is the detailed content of How does the Go `copy` function work with overlapping slices?. For more information, please follow other related articles on the PHP Chinese website!