为什么地图值不可寻址? [英] Why are map values not addressable?

查看:129
本文介绍了为什么地图值不可寻址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在玩Go代码时,我发现地图值不可寻址。例如,

  package main 
importfmt

func main(){
var mymap map [int] string = make(map [int] string)
mymap [1] =One
var myptr * string =& mymap [1]
fmt.Println(* myptr)
}

生成错误


mapaddressable.go:7:无法取得mymap的地址[1]

鉴于代码,

 包主
导入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)
}

完美无缺。



这是为什么? Go开发人员为什么选择使某些值不可寻址?这是语言的缺点还是功能?



编辑
从C ++背景来看,我不习惯这个不可寻址趋势似乎在Go中很普遍。例如,下面的代码工作得很好:

  #include< iostream> 
#include< map>
#include< string>
使用namespace std;
int main(){
map< int,string> MyMap中;
mymap [1] =one;
string * myptr =& mymap [1];
cout<< * myptr;

$ / code>

如果有人能指出为什么相同的可寻址性在Go中无法实现(或故意未实现)。

解决方案

我不知道内部执行映射,但很可能它是一种散列表。因此,如果您保存其中一个条目的地址,然后再放入一堆条目,则您保存的地址可能无效。这是由于哈希表的内部重组造成的,因为当加载因子超过特定阈值并且哈希表需要增长时。

因此,我猜测不允许按顺序获取其中一个条目的地址以避免此类错误。


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.

解决方案

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.

这篇关于为什么地图值不可寻址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆