Created
February 1, 2018 06:44
-
-
Save wudi/327d30e928c042f5af5e49ebf6089dae to your computer and use it in GitHub Desktop.
避免 string 转 []byte 开销的方式
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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