I know that as_ref() is a trait which is used for reference-to-reference conversion.I think with the '&' also we can do the same . in that case
what exactly is the usecase for as_ref() ?
when to use '&' and when to 'as_ref()' ?
I was trying below code and it gave error at line no 3. But line no 4 which has explicit type defined as &str works fine. why is it so? .
let a = String::from("foo");
let b = &a;
let c = a.as_ref(); //why this line gives compilation error
let d:&str = a.as_ref(); //and why this line works
To answer question 3, the trait AsRef is implemented for String for multiple output types, as indicated by the error message:
= note: multiple `impl`s satisfying `String: AsRef<_>` found in the following crates: `alloc`, `std`:
- impl AsRef<OsStr> for String;
- impl AsRef<Path> for String;
- impl AsRef<[u8]> for String;
- impl AsRef<str> for String;
Rust cannot infer which type is required, so the compiler requests an explicit type.
Generic code where you've intentionally added an AsRef bound only. You should never use AsRef::as_ref outside generic code, as it tends to make your code break later. If you want a reference to a, use &a.
(For clarity: this statement is only about the trait methodas_ref. Inherent methods like Option::as_ref are fine in non-generic code.)
If I understand it right, then the first isn't the same as the last two, but has the same name.
The first as_ref is doing a cheap conversion from one type to another (more precisely it converts a reference to a value into a reference to a value of a different type), while the last two create an ownedOptions/Results from a reference to an Option or a Result.