字符串与切片转换
本节内容主要代码位于 runtime/string.go, 基于 go1.16.4/amd64
以下面的代码进行说明
1 | slice := []byte{'h', 'e', 'l', 'l', 'o'} |
slice to string
底层将 byte slice 转换成 string 的函数为 slicebytetostring。
1 | func slicebytetostring(buf *tmpBuf, ptr *byte, n int) (str string) |
这个函数接收三个参数,*tmpBuf 是一个指向 byte 数组的指针,ptr 指向 slice 第一个元素的地址, n 表示切片的长度。