4 ms·
That was my first thought as well. If you keep mutable variables function-scoped, I see no difference between: // We do this: let point = Point { x: 2,
by suprfnk 7y ago
That was my first thought as well. If you keep mutable variables function-scoped, I see no difference between:
// We do this:
let point = Point { x: 2, y: 4 };
let point = Point { x: 4, ...point };
and
let point = Point { x: 2, y: 4 };
point.x = 4;
And that's generally what the problem is with mutable variables. You either erroneously assume `x == 2`, or have to read all the code between assignment and the point you're trying to change something.
Immutability gives you less thinking and parsing overhead. This kind of defeats that purpose.
- pixel_fcker 7y agoThe difference is the let key word makes it obvious you’re rebinding the name. Shadowing is one of those things that intuitively raises a red flag first time you see it but actually is extremely helpful. It dramatically reduces noise e.g. in functions where you take an input parameter and want to convert it to a different type to work with it. No more prefixing or suffixing the variable name, you just rebind it which makes the intent clear (at least to me).
- roblabla 7y agoYou can do this, but it's non-idiomatic (at least in my opinion). The only times I use shadowing is when "stripping a layer", such as unwrapping an option, or a non-destruction type change such as u8 to u64.
- jbboehr 7y agoIn many cases, due to Rust's move semantics, the previous value is consumed anyway. Imagine a function that takes and consumes a Point by value and returns a new, modified Point (assume we're talking about a struct without the Copy trait, as Point would likely have here). The original Point is no longer usable, and you may just want to replace it with the modified one. Yes, you could have the function (if it's yours) take a &mut Point but that precludes other references to it and using &mut unnecessarily isn't really considered good Rust AFAIK. From personal experience, this also makes it easy to set up `let y = f(g(x))` as easily reorderable or printf-debuggable statements in the form of `let y = x; let y = g(y); let y = f(y);`
- mamcx 7y agoI use also F# more, and is the same. But rust make some other guarantees/restrictions where this is much less of a problem that you think. Mutability is much restricted and the use of traits make conversions much easier. I think the best of rust is inmutability + From trait + Into Trait. Combined are great.