Skip to content

Instantly share code, notes, and snippets.

@wudi
Created February 1, 2018 06:44
Show Gist options
  • Select an option

  • Save wudi/327d30e928c042f5af5e49ebf6089dae to your computer and use it in GitHub Desktop.

Select an option

Save wudi/327d30e928c042f5af5e49ebf6089dae to your computer and use it in GitHub Desktop.
避免 string 转 []byte 开销的方式
package main
import (
"bufio"
"fmt"
"os"
"reflect"
"unsafe"
)
// s2b converts string to a byte slice without memory allocation.
//
// Note it may break if string and/or slice header will change
// in the future go versions.
func s2b(s string) []byte {
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh := reflect.SliceHeader{
Data: sh.Data,
Len: sh.Len,
Cap: sh.Len,
}
return *(*[]byte)(unsafe.Pointer(&bh))
}
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
hello, _ := reader.ReadString('\n')
fmt.Println(hello)
helloBytes := s2b(hello)
helloBytes[1] = 'w'
fmt.Println(hello)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment