Go字符串变量的显示大小似乎不真实

Tim*_*nov 0 memory-management runtime go

请参阅示例:http://play.golang.org/p/6d4uX15EOQ

package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

func main() {
    c := "foofoofoofoofoofofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoo"
    fmt.Printf("c: %T, %d\n", c, unsafe.Sizeof(c))
    fmt.Printf("c: %T, %d\n", c, reflect.TypeOf(c).Size())
}
Run Code Online (Sandbox Code Playgroud)

输出:

c: string, 8 //8 bytes?!
c: string, 8
Run Code Online (Sandbox Code Playgroud)

好像这么大的字符串不能有这么小的尺寸!出了什么问题?

pet*_*rSO 8

包装不安全

导入"不安全"

功能尺寸

func Sizeof(v ArbitraryType) uintptr
Run Code Online (Sandbox Code Playgroud)

Sizeof返回值v占用的字节大小.大小仅为值的"顶级".例如,如果v是切片,则返回切片描述符的大小,而不是切片引用的内存大小.

Go编程语言规范

长度和容量

len(s)    string type      string length in bytes
Run Code Online (Sandbox Code Playgroud)

您正在查看"顶级",string描述符,指针和底层字符串值的长度.使用len函数获取基础字符串值的长度(以字节为单位).

在概念上和实际上,字符串描述符是struct包含指针和长度的,其长度(32或64位)是依赖于实现的.例如,

package main

import (
    "fmt"
    "unsafe"
)

type stringDescriptor struct {
    str *byte
    len int
}

func main() {
    fmt.Println("string descriptor size in bytes:", unsafe.Sizeof(stringDescriptor{}))
}
Run Code Online (Sandbox Code Playgroud)

输出(64位):

string descriptor size in bytes: 16

输出(32位):

string descriptor size in bytes: 8