Skip to content
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

replace parameters order matter #90378

Closed
Stargateur opened this issue Oct 28, 2021 · 1 comment
Closed

replace parameters order matter #90378

Stargateur opened this issue Oct 28, 2021 · 1 comment

Comments

@Stargateur
Copy link
Contributor

Stargateur commented Oct 28, 2021

replace can be annoying to use as one liner because of the borrow checker, a good solution is to swap arguments order:

fn main() {
    let mut i = 0;
    
    assert_eq!(0, replace(i + 1, &mut i));
    assert_eq!(1, std::mem::replace(&mut i, i + 1));
    assert_eq!(2, i);
}

fn replace<T>(src: T, dest: &mut T) -> T {
  core::mem::replace(dest, src)
}
rror[E0503]: cannot use `i` because it was mutably borrowed
 --> src/main.rs:5:45
  |
5 |     assert_eq!(1, std::mem::replace(&mut i, i + 1));
  |                   ----------------- ------  ^ use of borrowed `i`
  |                   |                 |
  |                   |                 borrow of `i` occurs here
  |                   borrow later used by call

Unfortunately, in my knowledge even Rust edition can't allow this breaking change, I see potential solution:

  1. add a new function in mem module (what name ? replace2() ?)
  2. breaking change somehow
  3. do nothing and live with it
@Dylan-DPC
Copy link
Member

Closing this to clean up the issue tracker. if you need to use it you can use the workaround that you posted as an example

@Dylan-DPC Dylan-DPC closed this as not planned Won't fix, can't repro, duplicate, stale Feb 19, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants