Chi's Journal

- Ecclesiastes 1.11

Sep 1, 2019 - 1 minute read - Comments - program

golang []byte vs string

区别

  • []byte 是 slice,可以修改
  • string 是 read-only []byte

Strings are immutable: once created, it is impossible to change the contents of a string. 1

  • []byte 底层有 data, size, capacity, string 没有 capacity

string immutable 的含义指的是:

  • 一个 string 所在的内存区域内容是不改变的,比如 «hello»
  • 多个 string 可以共享(slice)同一个内存地址,比如 «el»
  • 原 string 变量(内存地址)被重新赋值之后,共享的变量们的值不会改变

package main

import "fmt"

func main() {
    a := "hello"
    b := a[0:2]
    fmt.Printf("a is at %x and has value %q\n", &a, a)
    fmt.Printf("b is at %x and has value %q\n", &b, b)

    a = "world"
    fmt.Printf("a is at %x and has value %q\n", &a, a)
    fmt.Printf("b is at %x and has value %q\n", &b, b)
}

/*
a is at 40c128 and has value "hello"
b is at 40c130 and has value "he"
a is at 40c128 and has value "world"
b is at 40c130 and has value "he"
*/

互转

  • []byte string 互转需要拷贝。2


参考

Tags: golang

comments powered by Disqus