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.
Code
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
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.