bytes.Copy returns the number of bytes copied, which is the minimum of the source and destination slice lengths.
The bytes.Copy function copies the minimum of len(src) and len(dst) elements, returning the count of bytes copied.
package main
import (
"bytes"
"fmt"
)
func main() {
dst := make([]byte, 3)
src := []byte("hello")
n := bytes.Copy(dst, src)
fmt.Println(n) // Output: 3
fmt.Println(string(dst)) // Output: hel
}
This behavior is by design to prevent buffer overflows; it never writes past the end of the destination slice.
The bytes.Copy function moves data from one slice to another but stops as soon as the destination is full or the source is empty. It acts like pouring water from a large pitcher into a small cup; once the cup is full, the pouring stops, and the function tells you exactly how much water you poured. This ensures you never accidentally overwrite memory beyond the intended destination.