1 package main
2
3 import "fmt"
4
5 func main() {
6
7 var numbers = []int{1, 2, 3, 4, 5}
8
9 // print original slice
10 fmt.Println("Original slice : ", numbers)
11
12 sliceCopy := make([]int, len(numbers), (cap(numbers))*2)
13 // copy slice into sliceCopy
14 copy(sliceCopy, numbers)
15 fmt.Printf("\nCopied slice : %v", sliceCopy)
16 }
1 Original slice : [1 2 3 4 5]
2
3 Copied slice : [1 2 3 4 5]
1 package main
2
3 import "fmt"
4
5 func main() {
6
7 var numbers []int
8
9 // length capacity of slice
10 fmt.Printf("Length = %d, and Capacity = %d", len(numbers), cap(numbers))
11
12 fmt.Printf("\nSlice : %v", numbers)
13
14 numbers = append(numbers, 10) // appending new element
15 numbers = append(numbers, 20, 30) // appending multiple elements
16 fmt.Printf("\nSlice : %v", numbers)
17
18 // after appending elements
19 fmt.Printf("\nLength = %d, and Capacity = %d", len(numbers), cap(numbers))
20
21 sliceCopy := make([]int, len(numbers), (cap(numbers))*2)
22
23 // copy slice into sliceCopy
24 copy(sliceCopy, numbers)
25 fmt.Printf("\nCopied slice : %v", sliceCopy)
26 }
1 Length = 0, and Capacity = 0 // initial copy and capacity
2 Slice : [] // initial element of slice
3 Slice : [10 20 30] // slice after appending elements
4 Length = 3, and Capacity = 3 // length and capacity after appending elements
5 Copied slice : [10 20 30] // content of copied slice