如何获取变量的内存大小?

问题描述:

有人知道如何获取变量(intstring[]struct等)的内存大小并进行打印吗?有可能吗?

Does anybody know how to get memory size of the variable (int, string, []struct, etc) and print it? Is it possible?

var i int = 1
//I want to get something like this:
fmt.Println("Size of i is: %?", i)
//Also, it would be nice if I could store the value into a string

您可以使用 unsafe.Sizeof 功能. 它返回以字节为单位的大小,该大小由您传入的值占用. 这是有效的示例:

You can use the unsafe.Sizeof function for this. It returns the size in bytes, occupied by the value you pass into it. Here's a working example:

package main

import "fmt"
import "unsafe"

func main() {
    a := int(123)
    b := int64(123)
    c := "foo"
    d := struct {
        FieldA float32
        FieldB string
    }{0, "bar"}

    fmt.Printf("a: %T, %d\n", a, unsafe.Sizeof(a))
    fmt.Printf("b: %T, %d\n", b, unsafe.Sizeof(b))
    fmt.Printf("c: %T, %d\n", c, unsafe.Sizeof(c))
    fmt.Printf("d: %T, %d\n", d, unsafe.Sizeof(d))
}

请注意,某些平台明确禁止使用不安全,因为它是不安全的.这曾经包括AppEngine.不确定今天是否仍然如此,但我想是这样.

Take note that some platforms explicitly disallow the use of unsafe, because it is.. well, unsafe. This used to include AppEngine. Not sure if that is still the case today, but I imagine so.

正如@Timur Fayzrakhmanov指出的那样,reflect.TypeOf(variable).Size()将为您提供相同的信息.对于reflect程序包,与unsafe程序包具有相同的限制.即:某些平台可能不允许其使用.

As @Timur Fayzrakhmanov notes, reflect.TypeOf(variable).Size() will give you the same information. For the reflect package, the same restriction goes as for the unsafe package. I.e.: some platforms may not allow its use.