Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The desugaring is an explanation of what's happening under the hood, but you don't need to think about that. Your mental model can simply be:

    for _ in x  // Consumes (moves) x and iterates over the values in x

    for _ in &x // Borrows x and iterates over references to the values in x


depends on what `into_iter` does in your type impl

ive always felt that there is something a bit strange about a keyword reaching into the stdlib (rust is not the only language that does this), especially if it's only for sugaring.


The alternative is duck-typing, hard-coding a method name, like Python’s __dunder__ methods. That’s just as strange. And for Rust, definitely unacceptable.

I think C++’s range-based for loops work this way, basically hard-coding .begin() and .end(). Oh, and only working on array-like things due to hard-coding ++ as the operator to go to the next item, so it’s less powerful than Rust.

It’s not a stable part of Rust, but you can provide your own definitions of lang items, not using even libcore. But they will need to be quite similar to the official one as the compiler will pretty much hard-code aspects of its definition.

An alternative view of it is that the standard library is reaching into the compiler. This feels just as accurate as the other way round. The two can’t reasonably be separated. A good fraction of Rust’s standard library is stuff that needs to be there, couldn’t be anywhere else.


> An alternative view of it is that the standard library is reaching into the compiler

Well, no not really, because it's a keyword (I don't know enough about rust internals to know if there are special parser rules for `for`)? You could put `for` in the stdlib instead. As rust has macros, you could in principle implement it as a macro.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: