Is there a temporary, anonymous object involved in creating maps in Go?

88 views Asked by At

I'm newly learning Go after primarily developing in C/C++ for a long time. So I still have a proclivity to analogize Go syntax to C/C++.

My Go tutor (ChatGPT :( ) told me that this is how you create + initialize a map (from string to int) in Go:

var foo = map[string]int{}

or

var foo = make(map[string]int)

To my C/C++-biased eyes, the use of the = looks like default-initialized variable foo is being assigned from a temporary, anonymous object of type map[string]int.
(ChatGPT hasn't explained make() to my satisfaction, but it still "looks like" there's implicitly a temporary, anonymous object involved because of a presumed object returned by make() assigned to foo with =)

My questions are:
Do the two statements above involve assignment from temporary, anonymous objects?
If yes, (how) can you instantiate (and default-initialize) a map object in Go without involving any temporary, anonymous objects?

What I've tried:
Neither of the following appear to be valid in Go:

var foo map[string]int
var foo map[string]int{}

I'm analogizing this Go syntax to the C++ "equivalent" of

std::map<string, int> foo;

vs.

std::map<string, int> foo = map<string, int>();
1

There are 1 answers

0
user229044 On

var x = y (or x := y) is how you declare a variable and initialize it with a value in Go. The alternate syntax you're looking for does not exist, and there is no "temporary variable" created here.

Looking for analogs to C++ is not useful. A map is not a C++ class. It is "copied" by reference.

Even if you run the following code...

var m1 = map[string]int{}
var m2 = m1

...you're still not copying anything.