Monday, April 27, 2015

Go Slice Functions - append and copy - Code Example

If you are new to Slices read the basics of slices here.

Go has two built-in functions to facilitate appending and copying with Slices:

1. append

As explained in the last article, unlike the fixed length arrays slices are dynamic in nature. append is a function that facilitate expansion of slices.

2. copy

copy function copies elements from a source to destination & returns the number of elements copied.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import "fmt"

func main() {
 
     slice1 := []int{11,22,33,44,55}
     fmt.Println("Slice1 = ", slice1)
 
     slice2 := append(slice1, 66,77,88)
     fmt.Println("Slice2 = ", slice2)
 
     slice3 := append(slice1, 99)
     fmt.Println("Slice3 = ", slice3)
 
     slice4 := append(slice2, 99)
     fmt.Println("Slice4 = ", slice4)
 
     sliceWorkingDays := []string{"Mon", "Tue", "Wed", "Thu", "Fri"}
     sliceWeekDays := append(sliceWorkingDays, "Sat", "Sun")
     fmt.Println("Working Days = ", sliceWorkingDays )
     fmt.Println("Week Days = ", sliceWeekDays)
     fmt.Println("Weekends =", sliceWeekDays[5:])
}



Output


You can play with the above code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import "fmt"

func main() {    
    slice1 := []int{1,2,3}     
    slice2 := make([]int, 3) // Change 3 to 1 and note the results
    slice3 := []int{2,4,6}
      
    copy(slice2, slice1)    
    fmt.Println("Slice1 = ", slice1, "| Slice2 = ", slice2) 
 
    copy(slice2, slice3)    
    fmt.Println("Slice1 = ", slice1, "| Slice2 = ", slice2, "| Slice3 = ", slice3) 
}


You can play with the above code here

Question

What is the output of below snippet?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import "fmt"

func main() {    
    slice1 := []int{1,3,5,7}     
    slice2 := []int{2,4,6,8}
  
    fmt.Println("Slice1 = ", slice1, "| Slice2 = ", slice2) 
      
    copy(slice2, slice1[:])    
    fmt.Println("Slice1 = ", slice1, "| Slice2 = ", slice2)
}

Answer


No comments:

Post a Comment