-
Notifications
You must be signed in to change notification settings - Fork 19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add Vec::last_or_push and friends #465
Comments
I'm willing to make a PR with this if everyone's okay with these changes as-is. |
Note: It might be a good idea to have |
I think having a |
At that point, why not have |
Any discussion on this? Like I said, if we're fine with it then I can make a pull request and such. |
The libs team has a backlog of these to get through, be patient. Personally, I think the |
Ah, they do? Is it publicly available? |
It's all the issues like yours with the ACP label:
api-change-proposal
|
👍 for shipping Sadly I don't think the borrow checker will let you get away with |
We discussed this in a libs-api meeting (with somewhat limited attendance), and those present were in favor of adding With match v.last_mut() {
None => v.push_mut(x),
Some(r) => r,
}
So, we're approving |
Speaking for myself: if |
This is OK in local use, but it falls afoul of borrowck limitations if you need to return that lifetime: playground |
That's the well-known case that's already on the list of things we want to change in the future, right? Makes me still want to hold off on adding a specific API for it unless we find out that it's extraordinarily common. (Or we find out that the borrowck changes are even further out than expected.) |
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 as
With this, this could be the following:
which is much nicer.
Solution sketch
Add functions for
Vec::last_or_push(T) -> &T
,Vec::last_mut_or_push(T) -> &mut T
,Vec::last_or_push_with(impl FnOnce() -> T) -> &T
,Vec::last_mut_or_push_with(impl FnOnce() -> T) -> &mut T
, which would get the last element of the vector, or push a value and return a reference to that.Alternatives
Alternatively,
Vec::push
could return&mut T
, which would remove the possiblity of a panic - maybe it would be better, but both would be nice. See issue #464.The text was updated successfully, but these errors were encountered: