Evaluate unsafe slices and strings safely
Evaluate unsafe slices and strings safely
unsafe.Slice constructs a slice view from a pointer and a length. The backing storage must contain enough correctly typed elements for the entire view. unsafe.String creates a string view over bytes that must remain immutable for as long as that string exists. Ordinary slices and conversions are preferred.
package main
import ( "fmt" "unsafe")
func main() { a := [3]int{4, 5, 6} v := unsafe.Slice(&a[0], len(a)) v[1] = 9 fmt.Println(a, len(v), cap(v))}This is confined to an owned array and uses its exact length. Slice creates an alias, not a copy; changing v changes a. The equivalent a[:] is safer. SliceData gives a pointer to slice storage, with special rules for nil and empty slices; do not dereference an empty slice pointer. Never extend a view beyond its allocation.
Expected output:
[4 9 6] 3 3Prefer an ordinary string conversion
package main
import ( "fmt")
func main() { b := []byte("tea") s := string(b) b[0] = 's' fmt.Println(s, string(b))}The ordinary conversion preserves the immutable string even when the slice changes. An unsafe.String alias requires the bytes to remain unmodified while the string exists. StringData returns a pointer to string bytes that must never be modified; for an empty string the result is unspecified and may be nil. unsafe.String and the data helpers arrived in Go 1.20; unsafe.Slice arrived in Go 1.17. No string mutation through unsafe is demonstrated.
Expected output:
tea seaTry it locally
Use a normal slice to share an array, and verify that changing the slice changes the array.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Reflection and unsafe 08: Evaluate unsafe slices and strings safely
Check the lesson objective before moving on.
What does unsafe.Slice create?
What must remain true while an unsafe.String result exists?