前往:数组和映射是否必须具有不同的概念/功能? [关闭]

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.

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.

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.