copy Copies Min Of Dst And Src

copy moves min(len(dst), len(src)) elements and returns that count, so short destinations silently truncate and you can detect it.

GoData Integrity

Code

gosnippet
22 lines
package main

import "fmt"

func main() {
	dst := make([]int, 2)
	src := []int{10, 20, 30, 40}

	// copy copies min(len(dst), len(src)) elements:目标短就静默截断
	n := copy(dst, src)
	fmt.Println("copied:", n, "dst:", dst, "src intact:", src)

	// 反过来:目标更长,源更短——只搬源的全部 2 个
	dst2 := make([]int, 4)
	m := copy(dst2, dst)
	fmt.Println("copied:", m, "dst2:", dst2)

	// copy 也能直接从字符串搬到 []byte
	buf := make([]byte, 3)
	k := copy(buf, "gopher")
	fmt.Println("copied:", k, "buf:", string(buf))
}

Inside the logic

copy Copies Min Of Dst And Src is built around the function main.

Using it

The file announces its steps in the output: copied:.

Output is labeled for readability — expect lines prefixed with copied:.

Key statements

dst2 := make([]int, 4)
buf := make([]byte, 3)
dst := make([]int, 2)

Interactive Tools for This Topic

FAQ

What does copy Copies Min Of Dst And Src print when run?
Running the file directly is enough — expect labeled output lines such as `copied:`.