How to assign string to bytes array

后端 未结 9 876
盖世英雄少女心
盖世英雄少女心 2020-12-12 08:59

I want to assign string to bytes array:

var arr [20]byte
str := \"abc\"
for k, v := range []byte(str) {
  arr[k] = byte(v)
}

Have another m

9条回答
  •  醉梦人生
    2020-12-12 09:18

    Besides the methods mentioned above, you can also do a trick as

    s := "hello"
    b := *(*[]byte)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&s))))
    

    Go Play: http://play.golang.org/p/xASsiSpQmC

    You should never use this :-)

提交回复
热议问题