3 ms·
For the record, I find Rust's ability to change the type of the variable _after_ it was declared to be absolutely bonkers for my ability to understand what is g
by ayende 5y ago
For the record, I find Rust's ability to change the type of the variable _after_ it was declared to be absolutely bonkers for my ability to understand what is going on in the code.
I understand what it is doing, but the fact that changing the return type of a method will change what previous code will compile to is something that I find extremely non obvious and surprising.
Inferring what the type is from the current code, sure. That saves me typing, but from what happens elsewhere looks like time travel.
- ReleaseCandidat 5y agoInteresting, I never thought about it this way. I just always find it a PITA that Rust can't do global type inference and that I have to type most of the types for myself.
- tialaramex 5y agoThe trouble is, when you say it's OK to infer "from the current code" that includes your function call, which is the thing where you're surprised it happens. There's no coherent reason why it'd be OK for Rust to conclude that x is a u64 from let x = some_u64.add(6); // the u64 type implement Add returning a u64 and yet not OK for Rust to conclude that x is a u64 from let x = someFunction(); // someFunction was defined to return u64 You had to explicitly change the return type of the method to cause yourself a surprise, Rust won't chase this rabbit through a warren, every individual function has to declare the types of its parameters and returns, so if you'd changed the function body not its declared return type, it could not have caused any change in type inference in other functions.
- ayende 5y agoThat isn't the problem. This is the issue: let x = str.parse()?; someFunc(x); The function called here is dependent on what `someFunc` will accept. That means that I can change what values will be accepted here by changing a completely different piece of code.
- ReleaseCandidat 5y agoOnly if you think of other code in the same function as 'a completely different piece of code'. With global type inference, the whole program is inferred for example.
- banana_maker 5y agoYou can always specify the type. let foo: T = bar.parse()?; // or let foo = bar.parse::<u32>()?; baz(foo); In my experience I've never found this to be surprising behavior, or unclear.
- timeon 5y agoThis is not going to solve your problem everywhere (certainly not when you are reading some github repo), but in the editor, rust analyzer will print the type from the beginning.