内容简介:string与[]byte经常需要互相转化,普通转化会发生底层数据的复制。如果是临时使用的字符串可以通过unsafe包直接转化数据,不需要内存拷贝这种方法有需要注意的地方,使用转化后的结果时必须要保证原内存还在,临时变量比较合适这种场景,如:byte2int
string与[]byte经常需要互相转化,普通转化会发生底层数据的复制。如果是临时使用的字符串可以通过unsafe包直接转化数据,不需要内存拷贝
func BytesToStringFast(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
func StringToBytes(s string) []byte {
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh := reflect.SliceHeader{sh.Data, sh.Len, 0}
return *(*[]byte)(unsafe.Pointer(&bh))
}
这种方法有需要注意的地方,使用转化后的结果时必须要保证原内存还在,临时变量比较合适这种场景,如:byte2int
func parseIntBytes(b []byte, base int, bitSize int) (i int64, err error) {
s := unsafeBytesToString(b)
return strconv.ParseInt(s, base, bitSize)
}
以上所述就是小编给大家介绍的《golang string与[]byte互》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Mobilizing Web Sites
Layon, Kristofer / 2011-12 / 266.00元
Everyone has been talking about the mobile web in recent years, and more of us are browsing the web on smartphones and similar devices than ever before. But most of what we are viewing has not yet bee......一起来看看 《Mobilizing Web Sites》 这本书的介绍吧!