How to copy one slice items into another slice in Golang?
The built-in copy function is used to copy data from one slice to another.
Example
package main
import "fmt"
func main() {
a := []int{5, 6, 7} // Create a smaller slice
fmt.Printf("[Slice:A] Length is %d Capacity is %d\n", len(a), cap(a))
b := make([]int, 5, 10) // Create a bigger slice
copy(b, a) // Copy function
fmt.Printf("[Slice:B] Length is %d Capacity is %d\n", len(b), cap(b))
fmt.Println("Slice B after copying:", b)
b[3] = 8
b[4] = 9
fmt.Println("Slice B after adding elements:", b)
}
Output
[Slice:A] Length is 3 Capacity is 3
[Slice:B] Length is 5 Capacity is 10
Slice B after copying: [5 6 7 0 0]
Slice B after adding elements: [5 6 7 8 9]
Most Helpful This Week
Golang program for implementation LIFO Stack and FIFO Queue
GO Program to Calculate Sum of Natural Numbers Using for.....Loop
GO Program to Check Whether a Number is Palindrome or Not
Illustration of Checkpoint Synchronization in Golang
Convert Int data type to Int16 Int32 Int64
How to Improve the Performance of Your Golang Application?