Junior — Middle
Kuidas töötab funktsioon copy Go keeles ja millistel juhtudel on selle kasutamine õigustatud?
sobes.tech AI
Vastus AI-lt
In Go, the copy function is used to copy elements from one slice to another. Its signature is:
func copy(dst, src []Type) int
copy copies at least the length of dst and src elements and returns the number of elements copied.
Its use is justified when you need to create a copy of a slice or copy part of the data into another slice, to avoid changing the original data when modifying the new slice.
Example:
src := []int{1, 2, 3, 4}
dst := make([]int, len(src))
count := copy(dst, src)
fmt.Println(dst) // [1 2 3 4]
fmt.Println(count) // 4
This is useful for creating independent copies of slices.