by junon · 1y ago · 0 comments
Because nothing in Rust is identifier-based. Unlike python, all syntax magic (even the ? operator) relies on traits defined by `core`.
for x in y {
desugars to let mut iter = IntoIterator::into_iter(y);
while let Some(x) = y.next() {
and x?
desugars to match x {
Ok(x) => x,
Err(e) => {
return Err(From::from(e));
}
}
and x + y
desugars to core::ops::Add::add(x, y)
etc.All of those traits are expected to live explicitly in the core crate at well known paths. Otherwise you'd be writing methods with absolutely no idea how the language would interact with it. And if you had a Set type implement `add`, it'd have to accept exactly 2 arguments to be compatible with the language's `add` or something equally as unergonomic.
It's traits all the way down! There'd be no explanation needed because it'd be antithetical and contradictory to traits to begin with. Once one understands how traits are intended to be used, the explanation for why there aren't identifier based resolution semantics becomes obvious.
Also, they don't need to live "at well known paths". Instead they're marked as "langitems", with the magic attribute lang:
#[lang = "add_assign"] // Signifies that this trait is what the compiler wanted to make the += operator work in the language.
Also AFAIR Try traits are relatively new, and are still unstable. Last I checked it was indeed a desugar to either From or Into (pretty sure it was From).
let mut iter = IntoIterator::into_iter(y);
instead of let mut iter = y.into_iter();
That could have been done, but it wasn't.> Otherwise you'd be writing methods with absolutely no idea how the language would interact with it.
Right, this is what's guessed, because it makes the most sense.
Anyway, my conclusion is that in order to learn Rust you can't use any syntactic sugar the language provides, those are 'expert features'. There's no way I'd be able to figure out why this happens. Do rust-analyzer provide a way of desugaring these constructs?
This is the common case in languages with sugar.
Heck, you could consider all of Rust sugar for MIR...
> There's no way I'd be able to figure out why this happens.
You don't generally need to, but most of this is documented:
https://doc.rust-lang.org/stable/std/iter/index.html#for-loo...
https://doc.rust-lang.org/stable/std/ops/trait.Add.html#impl...
?'s desugaring isn't documented because the desugaring is subject to change.