Size of memory a variable reference (not size of type of variable)

I would like to know the size of memory a variable references (not the size of the type of variable, which is just 8 bytes or 16bytes).
I’m using unsafe.Sizeof(a) , but that gives me only the size of the type of variable a, not the memory referenced by the variable.
s := "abc"
s1:= “abcedffffffffffffffff”

unsafe.SizeOf returns 16 bytes on both string however s1 holds more content. Knowing the size of memory referenced by s or s1 will help me in many cases, and in case where I need to load millions of strings into memory for quick access.


That isn’t exposed and is implementation specific - small allocations will typically be rounded up, and so on. The closest you’ll get without making assumptions on the implementation is probably sizeof(thestring) plus len(thestring).

Thanks for the reply. With the len of string, how do we know the size of it? Are we assuming the size of each character in the string?

len on a string returns the length in bytes.

I dont think it is accurate to assume each character is a byte, although it is good assumption.

len("string") returns the length of a string in bytes, as @calmh said, not number of runes (or characters). For example, try running this playground: What you’ll see is that the output is the length in bytes of a string and that they differ, even though the two strings have only one rune.

So, it’s fine to use len("string") to measure the size in bytes of a string’s content.


The size of a pointer to a variable is one machine word, uintptr, or more directly 4 bytes in 32 bit platforms, and 8 bytes on 64 bit platforms.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.