Let's start from:
pub fn read_dir<P: AsRef<Path>>(path: P) -> Result<ReadDir>
I can use this function with objects like:
let pb = PathBuf::from("/foo/bar");
let p = Path::new("/foo/bar");
let s = String::from("/");
Let's now say that I want to put both the variables into an Option<>
before unwrapping and calling read_dir()
, so one possible solution is to use something like:
let mut a: Option<&(dyn AsRef<Path>)>
The rationale here is that I want an option carrying a reference to different objects implementing the AsRef<Path>
trait. I don't want my Option<>
to carry the whole object, just its reference for the sake of optimization.
Give that, I can do something like (example nonsense code):
let mut op: Option<&(dyn AsRef<Path>)> = None;
let pb = PathBuf::from("/foo/bar");
let p = Path::new("/foo/bar");
let s = String::from("/");
op = Some(&pb);
op = Some(&p);
op = Some(&s);
if let Some(b) = op {
println!("{:?}", b.as_ref());
}
....
This code compiles fine and I'm here particularly interested in op = Some(&p)
that should be an Option<&Path>
. But Option<&Path>
is also returned from the parent()
function so I wast thinking that I could do something like:
let mut op: Option<&(dyn AsRef<Path>)> = None;
let pb = PathBuf::from("/foo/bar");
op = pb.parent();
Unfortunately this is returning
expected trait object `dyn std::convert::AsRef`, found struct `std::path::Path`
So my first question is: why?
While writing this example code I also realized that I have more problems with this code. For example I tried to do something like:
op = Some(pb.parent().unwrap());
That is returning an even more scary:
error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
At last I tried something like:
op = Some(&pb.parent().unwrap());
But this is returning a:
error[E0716]: temporary value dropped while borrowed
That leaves me a bit puzzled since I cannot guess which object / temporary is being freed since all I see are references to the pb
object.
I know that the code could be written differently avoiding the ugly Option<&(dyn ...
but it's just a toy code to learn more about trait objects & co.