go字符串转[]bytes

package main

import (
 "reflect"
 "unsafe"
)

func String2Bytes(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 Modify() {
     a := "hello"
     b := String2Bytes(a)
     b[0] = 'H'
}

func main() {
      Modify()
}

posted @ 2021-12-02 09:35  技术颜良  阅读(360)  评论(0编辑  收藏  举报