Skip to main content

Command Palette

Search for a command to run...

Conversion between array and slice

Published
1 min readView as Markdown
S
DevRel at StackGen | Formerly at Deepfence ,Tenable , Accurics | AWS Community Builder also Docker Community Award Winner at Dockercon2020 | CyberSecurity Innovator of Year 2023 award by Bsides Bangalore | Docker/HashiCorp Meetup Organiser Bangalore & Co-Author of Learn Lightweight Kubernetes with k3s (2019) , Packt Publication & also run Non Profit CloudNativeFolks / CloudSecCorner Community To Empower Free Education reach out me twitterhttps://twitter.com/sangamtwts or just follow on GitHub -> https://github.com/sangam14 for Valuable Resources

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:

package main

import "fmt"

func main() {
    s := []int{1, 2, 3}
    var a [3]int

    fmt.Println(copy(a, s))
}

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

package main

import "fmt"

func main() {
    s := []int{1, 2, 3}
    var a [3]int

    fmt.Println(copy(a[:2], s))
    fmt.Println(a)
}

The running output is:

2
[1 2 0]

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

package main

import "fmt"

func main() {
    a := [...]int{1, 2, 3}
    s := make([]int, 3)

    fmt.Println(copy(s, a[:2]))
    fmt.Println(s)
}

The execution result is:

2
[1 2 0]

References:
Arrays, slices (and strings): The mechanics of 'append'.

More from this blog

C

CloudNativeFolks Community

140 posts

CloudNativeFolks is non profit community that empower and educate about cloud native technology !