I have function that return Vec<PathBuf> and function that accept &[&Path], basically like this:
use std::path::{Path, PathBuf};
fn f(paths: &[&Path]) {
}
fn main() {
let a: Vec<PathBuf> = vec![PathBuf::from("/tmp/a.txt"), PathBuf::from("/tmp/b.txt")];
f(&a[..]);
}
Is it possible to convert Vec<PathBuf> to &[&Path] without memory allocations?
If not, how should I change f signature to accept slices with Path and PathBuf?
Is it possible to convert
Vec<PathBuf>to&[&Path]without memory allocations?
No, as answered by How do I write a function that takes both owned and non-owned string collections?; a PathBuf and a Path have different memory layouts (the answer uses String and str; the concepts are the same).
how should I change
fsignature to accept slices withPathandPathBuf?
Again as suggested in How do I write a function that takes both owned and non-owned string collections?, use AsRef:
use std::path::{Path, PathBuf};
fn f<P>(paths: &[P])
where P: AsRef<Path>
{}
fn main() {
let a = vec![PathBuf::from("/tmp/a.txt")];
let b = vec![Path::new("/tmp/b.txt")];
f(&a);
f(&b);
}
This requires no additional heap allocation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With