美文网首页
Go语言的string和byte slice之间的转换

Go语言的string和byte slice之间的转换

作者: L白水飘萍 | 来源:发表于2018-11-12 17:36 被阅读0次

    A string contains an array of bytes that, once created, is immutable. By contrast, the elements of a byte slice can be freely modified.

    Strings can be converted to byte slices and back again:

    s := “abc”

    b := []byte(s)

    s2 := string(b)

    Conceptually, the []byte(s) conversion allocates a new byte array holding a copy of the bytes of s, and yields a slice that references the entirety of that array. An optimizing compiler may be able to avoid the allocation and copying in some cases, but in general copying is required to ensure that the bytes of s remain unchanged even if those of b are subsequently modified. The onversion from byte slice back to string with string(b) also makes a copy, to ensure immutability of the resulting string s2。

    1 在Golang 中string 是不可改变的修改的。
    2 []byte转string的时候需要分配一次内存
    3 string 转[]byte的时候也需要分配一次内存

    相关文章

      网友评论

          本文标题:Go语言的string和byte slice之间的转换

          本文链接:https://www.haomeiwen.com/subject/pppcfqtx.html