3 ms·
Actually the type system catches that particular mistake: error[E0308]: mismatched types --> src/main.rs:5:6 | 5 | if x = 1 { |
by aethertap 10y ago
Actually the type system catches that particular mistake:
error[E0308]: mismatched types
--> src/main.rs:5:6
|
5 | if x = 1 {
| ^^^^^ expected bool, found ()
|
= note: expected type `bool`
= note: found type `()`
error: aborting due to previous error
error: Could not compile `playground`.
To learn more, run the command again with --verbose.
- tyingq 10y agoInteresting. Is there any plausible way that Rust can fall into the == vs = trap?
- aethertap 10y agoI haven't yet reached the level of Rust mastery where I'm confident in this answer, but as far as I can tell it's very hard to make that kind of mistake. I'd be very interested to hear what others have to say on it though.
- steveklabnik 10y agoNo, as assignment always results in (), and if always requires a boolean. This is by design.
- tyingq 10y agoAh...so this works: fn main() { let mut x = false; println!("{}", x); if {x=true;x} { println!("{}", x); } } But stands out as pretty obvious. Not something you might easily sneak into a codebase.
- steveklabnik 10y agoSneaky! Yeah, no way this should get past code review, and not even easy to accidentally type.