5

When I write this:

fn add1(vc: &mut Vec<usize>) {
    func1(vc, vc[0]);
}
fn func1(vc: &mut Vec<usize>, val: usize) {}

Clippy tells me that "writing &mut Vec instead of &mut [_] involves a new object where a slice will do".

However if I switch it to this:

fn add1(vc: &mut Vec<usize>) {
    func1(vc, vc[0]);
}
fn func1(vc: &mut [usize], val: usize) {}

I get "cannot borrow *vc as immutable because it is also borrowed as mutable [E0502]".

This makes sense, but why then did it work before?

Also, why is Clippy giving me incorrect warnings?

Link to working example

Link to not working example

LeopardShark
  • 3,820
  • 2
  • 19
  • 33
  • The difference is possibly because the coercion from `&mut Vec` to `&mut [usize]` involves a reborrow, whereas in the first example there is no coercion. – kaya3 Feb 09 '23 at 14:20
  • @kaya3 why would that make any difference? – Aharon Sambol Feb 09 '23 at 14:30
  • You can convert _both_ functions to take a slice: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=df126deeb71a3e2d2ef7f4bf8ecf8ba3 – user4815162342 Feb 09 '23 at 14:56
  • You can also call `as_mut()` to create an explicit `&mut [usize]` and use it for both arguments, which compiles: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=e39a8429394f342982e8a74d81f5ffda – user4815162342 Feb 09 '23 at 14:58
  • @user4815162342 "You can convert both functions to take a slice" In this example yes, but I'm more interested in why it's not working rather than how to fix it (rearranging the args also works in this example) – Aharon Sambol Feb 09 '23 at 15:01
  • 1
    The first (working) example triggers an implicit reborrow of `vc`, which apparently somehow happens _after_ processing the whole parameter list. The second (non-working) example triggers an unsized coercion, which apparently happens at the time the first parameter is encountered. This timing means that in the first case, `vc` is not borrowed yet when the second argument is processed, while in the second case it is. _Why_ the timing is like this, I have no idea, and there is no documentation about it. – Sven Marnach Feb 09 '23 at 15:42
  • order mater https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=67febe79366882f3dcb395073714f854, I don't even see how the first version compile but anyway – Stargateur Feb 09 '23 at 16:04
  • @Stargateur I mentioned that in my earlier comment, my question is about why it's happening rather than how to fix it – Aharon Sambol Feb 09 '23 at 17:13

0 Answers0