In a public number to see a copy of this problem although know will happen, but do not know there is this way to solve, reprint it to make a record.

We know that when a string is sliced, it makes a copy. Strictly speaking, memory copying occurs whenever a strong cast occurs. So here’s the question. Frequent memory copy operations don’t sound very performance friendly. Is there a way to slice a string without copying it?

package main\
\
import (\
 "fmt"\
 "reflect"\
 "unsafe"\
)\
\
func main() {\
 a :="aaa"\
 ssh := *(*reflect.StringHeader)(unsafe.Pointer(&a))\
 b := *(*[]byte)(unsafe.Pointer(&ssh))  \
 fmt.Printf("%v",b)\
} 
Copy the code
  • StringHeader 是stringIn the underlying structure of GO.
type StringHeader struct {
 Data uintptr
 Len  int
}
Copy the code
  • SliceHeader 是sliceIn the underlying structure of GO.
type SliceHeader struct {
 Data uintptr
 Len  int
 Cap  int
}
Copy the code
  • So if you want to convert the two at the bottom level, you just convertStringHeaderThe address of theSliceHeaderWill do. So go has a very strong package calledunsafe 。
    • 1.unsafe.Pointer(&a)Method to get variablesaThe address.
    • 2.(*reflect.StringHeader)(unsafe.Pointer(&a))The string A can be converted to the form of the underlying structure.
    • 3.(*[]byte)(unsafe.Pointer(&ssh))The SSH underlying structure can be converted into a pointer to a slice of byte.
    • 4. Through again*Convert to the actual content to which the pointer points.