Go: Do arrays and maps have to be different concepts/features?

huangapple go评论85阅读模式
英文:

Go: Do arrays and maps have to be different concepts/features?

问题

PHP中的数组可以同时使用数字键和字符串键。这太棒了。

例如:

$array[0] = "My value.";

或者

$array['key'] = "My value";

为什么Go语言没有像这样实现数组呢?

在Go语言中,为什么有两个不同的概念和语法(映射)会有好处?

我相信我没有看到这背后的有用之处。

英文:

Arrays in PHP work both with numeric keys and string keys. Which is awesome.

Ex:

$array[0] = "My value.";

or

$array['key'] = "My value";

Why doesn't go implement arrays like this?

What's the benefit for having two different concepts and syntax (maps) in Go?

I believe I'm failing to see the usefulness behind this.

答案1

得分: 12

Go不是PHP。虽然有一些高级语言共享这种抽象,但并不常见。数组和映射是不同目的的不同数据结构。

PHP的数组实际上是底层的哈希表。Go有真正的数组,并且它有切片,切片是对数组的更强大的抽象。

拥有真正的数组可以提供可预测的内存布局和真正的O(1)索引(对于Go的切片也是如此,它们在内部使用数组)。使用哈希映射作为底层数据存储会给所有操作带来恒定的开销,并且无法更好地控制数据局部性。

英文:

Go is not PHP. While a few higher-level languages share this abstraction, it's not very common. Arrays and Maps are different data structures for different purposes.

PHP's arrays are actually hash tables underneath. Go has true arrays, and it has slices which are a more powerful abstraction over arrays.

Having real arrays, gives you predictable memory layouts, and true O(1) indexing (the same goes for Go's slices, which use an array internally). Using a hash-map for the underlying data store costs you a constant overhead for all operations, as well as not being able to better control data locality.

答案2

得分: 3

一个主要的原因是数组有顺序,而映射没有顺序,这在这里1中有重要的影响:

当使用范围循环迭代映射时,迭代顺序没有指定,并且不能保证从一次迭代到下一次迭代是相同的。如果您需要稳定的迭代顺序,您必须维护一个单独的数据结构来指定该顺序。

英文:

One of the primary reason is that arrays have order, and maps do not, which has important implications as stated here:

> When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next. If you require a stable iteration order you must maintain a separate data structure that specifies that order.

huangapple
  • 本文由 发表于 2014年8月14日 03:11:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/25294290.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定