dongshi6844 2016-07-03 00:55
浏览 46
已采纳

为什么映射值不可寻址?

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.

展开全部

  • 写回答

2条回答 默认 最新

  • dsfdsf46465 2016-07-03 01:07
    关注

    Well I do not know about the internal Go implementation of maps but most likely it is a kind of hash table. So if you take and save the address of one of its entries and afterwards put another bunch of entries into it, your saved address may be invalid. This is due to internal reorganizations of hash tables when the load factor exceeds a certain threshold and the hash table needs to grow.
    Therefore I guess it is not allowed to take the address of one of its entries in order to avoid such errors.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部