Golang CopyN Function: Copy Bytes from Slice with Limit
The 'CopyN' function in Go is used to copy at most 'n' bytes from the source slice to the destination slice. It returns the number of bytes copied and an error if any.
The function signature is as follows:
func CopyN(dst []Type, src []Type, n int) int
Here, 'dst' is the destination slice, 'src' is the source slice, and 'n' is the maximum number of bytes to be copied.
Example:
package main
import (
"fmt"
)
func main() {
src := []byte('Hello, World!')
dst := make([]byte, 5)
n := CopyN(dst, src, 5)
fmt.Println(string(dst)) // Output: Hello
fmt.Println(n) // Output: 5
}
In this example, we have a source slice 'src' and a destination slice 'dst'. We want to copy at most 5 bytes from 'src' to 'dst'. We call the 'CopyN' function with 'dst', 'src', and 5 as arguments. The function returns the number of bytes copied, which is 5. We then print the contents of 'dst', which is 'Hello'.
原文地址: https://www.cveoy.top/t/topic/fYLg 著作权归作者所有。请勿转载和采集!