How does Vec implement Borrowmut?

I ran the following example in the standard library documentation, and there was a puzzle.

I found an implementation of the BorrowMut trait with Vec here
I don't understand how it works. For example, where the code below indicates that No.1 works, why doesn't No.2 work, what does the generic T do?

thanks

    use std::borrow::BorrowMut;

    fn check<T: BorrowMut<[i32]>>(mut v: T) {
        assert_eq!(&mut [1, 2, 3], v.borrow_mut()); //! no.1 can call, Why?
    }

    fn main() {
        let v = vec![1, 2, 3];
        // v.borrow_mut();  //! no.2 Can't call,Why?

        check(v);
    }

The type Vec<i32> implements both BorrowMut<Vec<i32>> and BorrowMut<[i32]>, so your call to .borrow_mut() is ambiguous as the compiler is unable to decide which one of them to call.

In check, all you know about T is that it implements BorrowMut<[i32]>, so it is unambiguous here.

1 Like

For example, this fails too:

fn check<T>(mut v: T)
where
    T: BorrowMut<[i32]>,
    T: BorrowMut<Vec<i32>>,
{
    assert_eq!(&mut [1, 2, 3], v.borrow_mut());
}
error[E0283]: type annotations needed
 --> src/lib.rs:8:34
  |
8 |     assert_eq!(&mut [1, 2, 3], v.borrow_mut()); // no.1 can call, Why?
  |                                --^^^^^^^^^^--
  |                                | |
  |                                | cannot infer type for type parameter `Borrowed` declared on the trait `BorrowMut`
  |                                this method call resolves to `&mut Borrowed`
  |
  = note: cannot satisfy `T: BorrowMut<_>`
help: use the fully qualified path for the potential candidates
  |
8 |     assert_eq!(&mut [1, 2, 3], <&mut T as BorrowMut<T>>::borrow_mut(v)); // no.1 can call, Why?
  |                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
8 |     assert_eq!(&mut [1, 2, 3], <T as BorrowMut<T>>::borrow_mut(v)); // no.1 can call, Why?
  |                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Here it fails because the compiler can't figure out which one to call.

Thanks for your reply, I understand.
So when I wrote the code in VScode, the phenomenon that this function v.borrow_mut could not be completed appeared, it should be a problem with Rust language service.
Thanks again.