Conversion between array and slice

In Go, array is a fixed length of continuous memory with specified type, while slice is just a reference which points to an underlying array. Since they are different types, they can’t assign value each other directly. See the following example:

  1. package main
  2. import "fmt"
  3. func main() {
  4. s := []int{1, 2, 3}
  5. var a [3]int
  6. fmt.Println(copy(a, s))
  7. }

Because copy only accepts slice argument, we can use the [:] to create a slice from array. Check next code:

  1. package main
  2. import "fmt"
  3. func main() {
  4. s := []int{1, 2, 3}
  5. var a [3]int
  6. fmt.Println(copy(a[:2], s))
  7. fmt.Println(a)
  8. }

The running output is:

  1. 2
  2. [1 2 0]

The above example is copying value from slice to array, and the opposite operation is similar:

  1. package main
  2. import "fmt"
  3. func main() {
  4. a := [...]int{1, 2, 3}
  5. s := make([]int, 3)
  6. fmt.Println(copy(s, a[:2]))
  7. fmt.Println(s)
  8. }

The execution result is:

  1. 2
  2. [1 2 0]

References:
In golang how do you convert a slice into an array;
Arrays, slices (and strings): The mechanics of ‘append’.