In Luciano Ramalho’s book Fluent Python Clear, Concise, and Effective Programming, 2nd Edition, there is one paragraph that says:
“Consider Go. Some objects in that language have features that are magic, in the sense that we cannot emulate them in our own user-defined types. For example, Go arrays, strings, and maps support the use brackets for item access, as in a[i]. But there’s no way to make the [] notation work with a new collection type that you define. Even worse, Go has no user-level concept of an iterable interface or an iterator object, therefore its for/range syntax is limited to supporting five “magic” built-in types, including arrays, strings, and maps.”
What does this paragraph mean exactly?
In Go, the use of square brackets []
for indexing is limited to built-in types such as arrays, slices, strings, and maps. For example, we can access the elements of an array using arr[i]
notation, where arr
is an array and i
is an index.
However, if we define our own collection type, we cannot use this notation directly. We would have to define a method that takes an index and returns the element at that index. Here’s an example: