The size of a variable can be determined by using unsafe.Sizeof(a)
. The result will remain the same for a given type (i.e. int
, int64
, string
, struct
etc), irrespective of the value it holds. However, for type string
, you may be interested in the size of the string that the variable references, and this is determined by using len(a)
function on a given string. The following snippet illustrates that size of a variable of type string is always 8 but the length of a string that a variable references can vary:
package main
import "fmt"
import "unsafe"
func main() {
s1 := "foo"
s2 := "foobar"
fmt.Printf("s1 size: %T, %d\n", s1, unsafe.Sizeof(s1))
fmt.Printf("s2 size: %T, %d\n", s2, unsafe.Sizeof(s2))
fmt.Printf("s1 len: %T, %d\n", s1, len(s1))
fmt.Printf("s2 len: %T, %d\n", s2, len(s2))
}
Output:
s1 size: string, 8
s2 size: string, 8
s1 len: string, 3
s2 len: string, 6
The last part of your question is about assigning the length (i.e. an int
value) to a string
. This can be done by s := strconv.Itoa(i)
where i
is an int
variable and the string
returned by the function is assigned to s
.
Note: the name of the converter function is Itoa
, possibly a short form for Integer to ASCII. Most Golang programmers are likely to misread the function name as Iota
.