Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of sizeof(aType) in Go

C++ and several other languages have a function called sizeof(int) (or whatever type 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?

like image 898
Vector Avatar asked Feb 02 '14 13:02

Vector


People also ask

How big is an int in Go?

int is one of the available numeric data types in Go . int has a platform-dependent size, as, on a 32-bit system, it holds a 32 bit signed integer, while on a 64-bit system, it holds a 64-bit signed integer.

How many bytes is a string in Go?

In Go Strings are UTF-8 encoded, this means each charcter called rune can be of 1 to 4 bytes long. Here,the charcter ♥ is taking 3 bytes, hence the total length of string is 7.

How do you find the size of a variable in Golang?

Sizeof() is the correct solution.


1 Answers

If you simply want to find out the size of an int or uint, use strconv.IntSize.

Package strconv

Constants

const IntSize = intSize

IntSize is the size in bits of an int or uint value.

For example,

package main

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

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

Output:

gc amd64 linux
64
like image 144
peterSO Avatar answered Oct 04 '22 16:10

peterSO