我对Golang中的地图数据结构感到困惑。让我说清楚,我明白当我执行以下操作。
m:= make([string] int)
m实际上是Golang中的runtimes.HashMap的指针。尽管它看起来不像一个,但实际上是一个指针变量。但是,假设我有以下代码。下面的代码构建了一个映射,其中包含字符串中每个字符的开始和结束索引。例如。映射[a] =元组{0,6}
type Tuple struct {
i int
j int
}
type tupleMap map[string]Tuple
a := "abcbfsagduisjgjxyx"
m := tupleMap{}
for index, c := range a {
if _, ok := m[string(c)]; !ok {
m[string(c)] = Tuple{index, index}
} else {
//this line below has error `cannot assign to struct field m[string(c)].j in map compiler`
m[string(c)].j = index
//If I want to assign index to j, I have to do the following...
entry := m[string(c)]
entry.j = index
m[string(c)] = entry
}
}
m [string(c)]。j =索引导致编译错误。我必须分3步来做。为什么是这样?
但是,如果我将地图值指定为&Tuple,则可以正常工作。请看下面的代码:
type Tuple struct {
i int
j int
}
type tupleMap map[string]*Tuple
a := "abcbfsagduisjgjxyx"
m := tupleMap{}
for index, c := range a {
if _, ok := m[string(c)]; !ok {
m[string(c)] = &Tuple{index, index}
} else {
//this works fine.
m[string(c)].j = index
}
}
我很困惑,请有人指出我正确的方向。 当我阅读Brian Kernighan编写的The Go Programming语言时,他们提到map元素不是变量,我们无法获取其地址。因此_:=&map [“ a”]将是编译错误。原因是增长的地图可能会导致将现有元素重新哈希到新的存储位置,从而可能使地址无效。我对此也很困惑。