Hacker News new | ask | show | jobs
by BeetleB 29 days ago
So you would be equally critical of overloading [] for maps?

Sorry, hard for me to relate, as I've overloaded [] (in, say, Python) to make life easy on everyone. People loved it.

I hope you're aware that there is a long standing debate on whether overloading operators is good/bad, and it comes down to personal preference?

1 comments

> So you would be equally critical of overloading [] for maps?

No, I'm not sure how you got that impression. Overloading is great.

It's also confusing when it does something completely different from what you intuitively expect.

If you're an old timer, you expect [] to index into an array, and you definitely do not expect it to do a lookup in a map/dict. Older languages just didn't include a dict-like structure in the language (technically, even C++ didn't).

Do you not see that for them, overloading [] for dictionary lookups is "something completely different from what you intuitively expect"?

More strikingly, C++ doesn't distinguish what Rust would call IndexMut and just Index, the use of the [idx] operator in a context where we'll mutate things and one where we don't want that.

Rust's HashMap implements Index because answer = map[name] is a perfectly reasonable thing to do, and if there is no key matching name then we panic, makes sense but it does not provide IndexMut so that you could write map[name] = answer because the edge cases are non-obvious so better to make you write what you meant.

C++ hash tables implement operator[] but the result is mutable, in order that map[name] = 123.0 can work which in Rust would be IndexMut and isn't provided. Because this is true, the index operation always succeeds, if you ask for map["not-present"] it creates the hash table entry for "not-present" and tries to store a default value ready to update it if you later assign to the reference.