String Internals

Fill in the blank in line A, to convert b from []byte to string without causing memory copy.The expected output is "143"

  1. package main
  2. import (
  3. "fmt"
  4. "unsafe"
  5. )
  6. func main() {
  7. var b = []byte("123")
  8. s := __ //A
  9. b[1] = '4'
  10. fmt.Printf("%+v\n", s) //print 143
  11. }

Answer

  1. package main
  2. import (
  3. "fmt"
  4. "unsafe"
  5. )
  6. func main() {
  7. var b = []byte("123")
  8. s := *(*string)(unsafe.Pointer(&b))
  9. b[1] = '4'
  10. fmt.Printf("%+v\n", s) //print 143
  11. }