Search code examples
govariablesmemoryconstants

Golang: How is memory allocated when using `const`/`var` vs in a function?


I'm looking for clarity on how memory is allocated/managed in Go. See example:

package main

// memory allocated on program startup?
var str1 = "Hello world!"

func createString() string {
  // memory allocated when function is called?
  var str2 = "Another string"
  return str2
}

In this example code, how does Go manage the memory of str1 and str2? Does the value of str1 hang out in memory during the entire runtime of the program?

Can I save on overall program memory usage if I declare string variables inside of function scopes rather than declaring them as global variables?


Solution

  • The string literals "Hello world!" and "Another string" will be in memory no matter how you declare the variables. The str1 will be initialized to point to "Hello world" literal before main starts, and str2 will be initialized to point to "Another string" when createString runs. Both str1 and str2 only contain a pointer and length, so they do not consume much memory.

    In short, you cannot save memory based on where you initalize a string using a literal. The literal is what occupies most of the memory, not the string variable.