Unsafe String Byte Zero Copy Conversions

Convert between string and []byte without copying via unsafe.String and unsafe.StringData, and state the read-only contract that keeps it safe.

GoData Integrity

Code

gosnippet
36 lines
package main

import (
	"fmt"
	"unsafe"
)

// stringToBytes 返回与 s 共享内存的字节视图:零拷贝,但必须只读
func stringToBytes(s string) []byte {
	if s == "" {
		return nil
	}
	return unsafe.Slice(unsafe.StringData(s), len(s))
}

// bytesToString 零拷贝 zero copy:切片内存直接视作 string
func bytesToString(b []byte) string {
	if len(b) == 0 {
		return ""
	}
	return unsafe.String(&b[0], len(b))
}

func main() {
	s := "header: v2"
	b := stringToBytes(s)
	fmt.Println("len match:", len(b) == len(s))
	fmt.Println("prefix:", string(b[:6]))

	shared := []byte{'p', 'i', 'n', 'g'}
	asString := bytesToString(shared)
	fmt.Println("string:", asString)
	// 转换后仍经原切片读取:两者共享同一块内存,
	// 任何一方写入都会破坏 string 的不可变契约
	fmt.Println("slice view equals:", string(shared) == asString)
}

How this snippet works

Unsafe String Byte Zero Copy Conversions keeps everything in the functions stringToBytes, bytesToString and main.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

Entry signature: func stringToBytes(s string) []byte

Steps are announced in the file’s output: len match:, prefix:, string:.

main sequences stringToBytes and bytesToString; executing the file runs that flow once.

Core lines

func stringToBytes(s string) []byte {
	if s == "" {
		return nil
	}
	return unsafe.Slice(unsafe.StringData(s), len(s))
}
func bytesToString(b []byte) string {
	if len(b) == 0 {
		return ""
	}
	return unsafe.String(&b[0], len(b))
}

Interactive Tools for This Topic

FAQ

What does Unsafe String Byte Zero Copy Conversions print when run?
Invoke the file as-is — the `len match:`, `prefix:`, `string:` prefixes identify which step printed each line.