While playing with Go code, I found out that map values are not addressable. For example,
package main
import "fmt"
func main(){
var mymap map[int]string = make(map[int]string)
mymap[1] = "One"
var myptr *string = &mymap[1]
fmt.Println(*myptr)
}
Generates error
mapaddressable.go:7: cannot take the address of mymap[1]
Whereas, the code,
package main
import "fmt"
func main(){
var mymap map[int]string = make(map[int]string)
mymap[1] = "One"
mystring := mymap[1]
var myptr *string = &mystring
fmt.Println(*myptr)
}
works perfectly fine.
Why is this so? Why have the Go developers chosen to make certain values not addressable? Is this a drawback or a feature of the language?
Edit:
Being from a C++ background, I am not used to this not addressable
trend that seems to be prevalent in Go. For example, the following code works just fine:
#include<iostream>
#include<map>
#include<string>
using namespace std;
int main(){
map<int,string> mymap;
mymap[1] = "one";
string *myptr = &mymap[1];
cout<<*myptr;
}
It would be nice if somebody could point out why the same addressability cannot be achieved (or intentionally wasn't achieved) in Go.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…