Closed balt-dev closed 2 hours ago
I'm willing to make a PR with this if everyone's okay with these changes as-is.
Closing in favor of #465
I think this is 100% more correct, but sadly it's a breaking change today.
I'd love for someone to come up with enough language features that it would no longer be breaking!
What do you mean? No matter what, this - changing the return type of a function - is always a breaking change.
That's true of Rust today, but maybe in a future Rust it wouldn't need to be.
Imagine if you could coerce a fn(&mut Vec<T>, T) -> &mut T
to fn(&mut Vec<T>, T) -> ()
, for example -- that'd remove one way that this a change like this is breaking. Then it'd "just" be a matter of doing changes like that for all the reasons that something might be breaking.
Proposal
Problem statement
Getting a reference to the value you just pushed to a vector requires an extra call and unwrap:
Motivating examples or use cases
I'm currently porting https://github.com/Naruyoko/OmegaNum.js/ to Rust, and this is a common pattern all over:
x.array[i+1]=(x.array[i+1]||0)+1;
This is directly translated asWith this, this could be the following:
which is much nicer.
Solution sketch
Change
Vec::push
to return a reference to the pushed value:Alternatives
Alternatively,
Vec::last_or_push(default: T) -> &T
, along with 3 other variations for mutability and laziness, could make the above translate in only one line - maybe it would be better, but both would be nice. See issue #465.