Equivalent to sizeof (aType) in Go

C ++ and several other languages ​​have a function called sizeof(int)(or any other type that you need) that returns the number of bytes consumed by a particular data type in the current system.

Is there an equivalent function in Go? What is it?

+4
source share
4 answers

If you want to know the size of a certain value, there are two ways to do this - use an unsafe package or use a reflection package. The following code demonstrates both:

package main

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

func main() {
    var i int
    fmt.Printf("Size of var (reflect.TypeOf.Size): %d\n", reflect.TypeOf(i).Size())
    fmt.Printf("Size of var (unsafe.Sizeof): %d\n", unsafe.Sizeof(i))
}

However, I do not know how to get the type size directly. But I think you will find out that the sizeof function is not needed as often as in C.

+6
source

sizeof go unsafe.Sizeof. sizeof C , ( C ). , - , C .

:

package main

import (
    "fmt"
    "unsafe"
)

func main() {
    fmt.Println(unsafe.Sizeof(int(0)))
}
+7

int uint, strconv.IntSize.

strconv

Constants

const IntSize = intSize

IntSize - int uint.

,

package main

import (
    "fmt"
    "runtime"
    "strconv"
)

func main() {
    fmt.Println(runtime.Compiler, runtime.GOARCH, runtime.GOOS)
    fmt.Println(strconv.IntSize)
}

:

gc amd64 linux
64
+4

, & hellip;

, :

  • ( ): interface{} .

    : . gc ( gccgo, ) , , & leq; uintptr .

  • (, ): ( ); reflect. , unsafe.Pointer, , gc , / unsafe.Pointer.

    , . , .

+2

Source: https://habr.com/ru/post/1524929/


All Articles