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).
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: https://play.golang.org/p/xbC-S2Z7rR. 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.