Go How to Convert Array to Slice with Example
In Go, you convert an array to a slice by using the slice expression
array[:], which creates a slice referencing the entire array.Examples
Input[1, 2, 3]
Output[1 2 3]
Input[10, 20, 30, 40]
Output[10 20 30 40]
Input[0, 0, 0]
Output[0 0 0]
How to Think About It
To convert an array to a slice in Go, think of a slice as a flexible window over the array. By using
array[:], you create a slice that points to the whole array without copying it. This lets you work with the array elements more easily and dynamically.Algorithm
1
Start with a fixed-size array.2
Use the slice expression <code>array[:]</code> to create a slice referencing the entire array.3
Use the slice as needed for flexible operations.Code
go
package main import "fmt" func main() { arr := [3]int{1, 2, 3} slice := arr[:] fmt.Println(slice) }
Output
[1 2 3]
Dry Run
Let's trace converting array [1, 2, 3] to a slice.
1
Define array
arr = [1, 2, 3]
2
Create slice from array
slice = arr[:]
3
Print slice
Output: [1 2 3]
| Step | Array | Slice |
|---|---|---|
| 1 | [1 2 3] | nil |
| 2 | [1 2 3] | [1 2 3] |
| 3 | [1 2 3] | [1 2 3] |
Why This Works
Step 1: Array and Slice Relationship
An array is a fixed-size collection, while a slice is a flexible view over an array using array[:].
Step 2: Slice Expression
Using array[:] creates a slice that points to the entire array without copying data.
Step 3: Usage
The slice can be used like a dynamic list, allowing easier manipulation than the fixed array.
Alternative Approaches
Slice a part of the array
go
package main import "fmt" func main() { arr := [5]int{10, 20, 30, 40, 50} slice := arr[1:4] // slice from index 1 to 3 fmt.Println(slice) }
This creates a slice of a subset of the array, useful when you want only part of the array.
Create a new slice and copy array elements
go
package main import "fmt" func main() { arr := [3]int{1, 2, 3} slice := make([]int, len(arr)) copy(slice, arr[:]) fmt.Println(slice) }
This copies array elements into a new slice, useful if you want an independent slice.
Complexity: O(1) time, O(1) space
Time Complexity
Creating a slice with array[:] is O(1) because it just creates a view, but copying elements is O(n).
Space Complexity
Using array[:] uses O(1) extra space since no new array is created; copying uses O(n).
Which Approach is Fastest?
Slicing with array[:] is fastest and most memory efficient; copying is slower but creates independent data.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Slice entire array with array[:] | O(1) | O(1) | Fast, no copy, flexible view |
| Slice part of array with array[start:end] | O(1) | O(1) | Partial view without copy |
| Copy array to new slice | O(n) | O(n) | Independent slice, safe from array changes |
Use
array[:] to quickly get a slice referencing the whole array without copying.Trying to assign an array directly to a slice variable without slicing causes a type mismatch error.