Golang: Copy Slice
Copy Slice
copy(dst, src)
-
- Copy elements of slice from src to dst.
- The number of elements copied is the smaller of lengths of argument, whichever is shorter.
- It wipes the values in the dst slice starting at index 0.
- Return the number of items copied.
- Arguments must be slice of the same type.
- In the case of byte slice, the src can be a string too.
package main import "fmt" func main() { var x = []int{0, 1, 2, 3, 4, 5} var y = []int{99, 999} copy(y, x) fmt.Println(y) // [0 1] }
Example of copying shorter to longer:
package main import "fmt" func main() { var x = []int{99, 999} var y = []int{0, 1, 2, 3, 4, 5} copy(y, x) fmt.Println(y) // [99 999 2 3 4 5] }
Golang, array and slice
- Golang: Array
- Golang: Slice
- Golang: Slice of Slice
- Golang: Append to Slice
- Golang: Cut Slice (Delete Elements)
- Golang: Copy Slice
- Golang: Clear Slice
- Golang: Nested Slice
- Golang: Slice of Strings to String
- Golang: Iterate Slice
- Golang: Convert Value to String
- Golang: Convert Array to Slice
- Golang: Print Slice, Array