szaydel
3/8/2018 - 5:54 PM

Golang Snippet - Using Unsafe Pointer for slice mutation

Example usage of unsafe pointer for mutating a slice, as an alternative to using indexing into the slice.

package main

import (
	"fmt"
	"unsafe"
)

type X struct {
	i int
}

var slice = []X{
	X{i: 1},X{i: 2},X{i: 3},
}

const (
	limit = 10
)

func main() {
	start := unsafe.Pointer(&slice[0])
	size := unsafe.Sizeof(slice[0])
	for i := 0 ; i<len(slice) ; i++  {	
	p := (*X)(unsafe.Pointer(uintptr(start) + size*uintptr(i)))
	(*X)(p).i += 10
	fmt.Printf("Slice item ptr=%p | value=%d\n", p, *p)
	}
	fmt.Printf("Result: %v\n", slice)
}