3 ms·
C++: void f(map<int, int> m) { m[0] = 0; } int main() { map<int, int> t; t[0] = 1; f(t); cout << t[0] << endl; return 0; } print
by YZF 10y ago
C++:
void f(map<int, int> m)
{
m[0] = 0;
}
int main() {
map<int, int> t;
t[0] = 1;
f(t);
cout << t[0] << endl;
return 0;
}
prints 1.
Go:
func f(m map[int]int) {
m[0] = 0
}
func main(){
var t = make(map[int]int)
t[0] = 1
f(t)
fmt.Println(t[0])
}
Prints 0.
So in C++ maps are passed by value.
In Go they are passed by, hmm, "not value".
Go could have made maps similar to C++ maps and then people could use a pointer to a map when they wanted that. As it stands maps are "different" which is not a big deal once you're used to it but still makes things a little weird if you're coming from C++.