如何在Go中有效地将字符串转换为字节切片,包括最后的0?

时间:2018-06-13 03:16:42

标签: string go slice

我想将字符串转换为字节切片,包括最后的0个字符。

我知道以下代码将字符串转换为切片:

my_slice := []byte("abc")

以下代码可以添加最终的0个字符:

my_slice = append(my_slice , 0)

但我想知道它是否可以更高效地完成,可能在一行,因为两行都会分配内存。

效率低下的例子:https://play.golang.org/p/Rg6ri3H66f9

2 个答案:

答案 0 :(得分:1)

分配所需长度的切片。将字符串复制到切片。

s := "abc"
my_slice := make([]byte, len(s)+1)
copy(my_slice, s)

没有必要将最后一个元素设置为零,因为make返回一个切片,所有元素都设置为零。

答案 1 :(得分:0)

高效的单行方法是内联函数调用。例如,

package main

import "fmt"

func cstring(s string) []byte {
    b := make([]byte, len(s)+1)
    copy(b, s)
    return b
}

func main() {
    s := "abc"
    fmt.Printf("%q\n", s)

    c := cstring(s) // inlining call to cstring

    fmt.Printf("%q\n", c)
}

优化决策:

$ go tool compile -m cstring.go
cstring.go:5:6: can inline cstring
cstring.go:15:14: inlining call to cstring
cstring.go:6:11: make([]byte, len(s) + 1) escapes to heap
cstring.go:5:14: cstring s does not escape
cstring.go:13:13: s escapes to heap
cstring.go:15:14: make([]byte, len(s) + 1) escapes to heap
cstring.go:17:13: c escapes to heap
cstring.go:13:12: main ... argument does not escape
cstring.go:17:12: main ... argument does not escape
$

输出:

$ go run cstring.go
"abc"
"abc\x00"
$

游乐场:https://play.golang.org/p/7gi9gR7iWkS