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.
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.