Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

《如何实现字符串和byte切片的零拷贝转换》章节,在1.20版之后有变化了 #61

Open
ilaziness opened this issue Feb 7, 2023 · 1 comment

Comments

@ilaziness
Copy link

问题描述

《如何实现字符串和byte切片的零拷贝转换》章节,在1.20版之后有变化了,原方法后面会不适用了。

新的方法:

func StringToBytes(s string) []byte {
    return unsafe.Slice(unsafe.StringData(s), len(s))
}

func BytesToString(b []byte) string {
    return unsafe.String(&b[0], len(b))
}
@molon
Copy link

molon commented Feb 25, 2023

针对于 BytesToString 发现两个参考:

  • unsafe.String(unsafe.SliceData(b), len(b)) 源自 strings.Builder String()
  • unsafe.String(&b[0], len(b)) 源自 strings.Clone
    个人也是倾向于后者,但这个确实对强迫症患者造成了一些纠结,哈哈。

不过需要注意使用后者的话,需要先判断长度

func BytesToString(b []byte) string {
	if len(b) == 0 {
		return ""
	}
	return unsafe.String(&b[0], len(b))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants