go / intermediate
Snippet
Converting Slices to Array Pointers for Fixed Size Guarantees
In Go, slices can be converted directly into array pointers when the slice size matches or exceeds the array length. This allows passing slices to functions expecting fixed-size arrays without copying the elements, providing strict size validation at runtime.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package mainimport "fmt"func processThreeElements(arr *[3]int) {arr[0] = 100arr[1] = 200arr[2] = 300}func main() {slice := []int{10, 20, 30}arrPtr := (*[3]int)(slice)processThreeElements(arrPtr)fmt.Println("Modified Slice:", slice)}
Breakdown
1
func processThreeElements(arr *[3]int) {
A function that expects a pointer to a fixed-size array of 3 elements.
2
arrPtr := (*[3]int)(slice)
Converts the slice to an array pointer of size 3. Panics at runtime if the slice length is less than 3.
3
processThreeElements(arrPtr)
Passes the array pointer to the function, sharing the slice's underlying storage directly.