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

以下摘自The Go Programming Language

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 conversion from byte slice back to string with string(b) also makes a copy, to ensure immutability of the resulting string s2.

由于Go语言中字符串是不可修改的,因此如果要修改其中内容,就要把其转化成byte slice。此外,byte slice也可以转化成字符串。这两种转化都需要分配一块新的内存,然后进行内容拷贝。

 

《Go语言的string和byte slice之间的转换》有1个想法

  1. hello,请问:在string类型里:
    str := “hello”
    str = str[2:3]

    这种写法是ok的(能够运行),但我看有些地方说string是fix-sized,(空间不能变化),这是不是冲突了?
    我的理解是:string的底层实现是也是由指针和字符数组构成的,底层的字符数组不能修改
    上面的str[2:3]只是修改了指针的指向(但依然指向的是同一个底层字符数组)

    不知道理解的对不对?

    另外:研究dtrace的国人好像不多,我知道春哥(openresty的作者)在这方面造诣很深,或许你们可以交流下~~ (http://openresty.org/en/)

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.