我正在使用std::fs
中的函数,这些函数带有path: impl AsRef<Path>
之类的参数。我希望使自己的函数具有多态性,以便它们也可以采用任何impl AsRef<Path>
而不是仅接受&str
。但是,所讨论的类似路径的对象必须存储在我的结构之一中。这意味着必须将其存储为Box<dyn AsRef<Path>>
才能赋予它已知的大小。我正在努力将此装箱的值转换为std::fs
函数可以接受的任何值。
考虑以下代码:
use std::path::Path;
fn main() {
fn polymorphic(_: impl AsRef<Path>) {}
let boxed: Box<dyn AsRef<Path>> = Box::new("/foo/bar");
polymorphic(/*???*/);
}
我可以用什么替换问号,以便我可以用
polymorphic
调用"/foo/bar"
?
最佳答案
取消引用并重新引用Box
:
use std::path::Path;
fn main() {
fn polymorphic(_: impl AsRef<Path>) {}
let boxed: Box<dyn AsRef<Path>> = Box::new("/foo/bar");
polymorphic(&*boxed);
}
This means it must be stored as
Box<dyn AsRef<Path>>
不,不是。
Path
状态(重点是我的)的文档:This is an unsized type, meaning that it must always be used behind a pointer like
&
orBox
. For an owned version of this type, seePathBuf
.
use std::path::{Path, PathBuf};
fn polymorphic(_: impl AsRef<Path>) {}
struct Example(PathBuf);
impl Example {
fn new(path: impl AsRef<Path>) -> Self {
Self(path.as_ref().to_owned())
}
fn example(&self) {
polymorphic(&self.0)
}
}
我实际上会自己使用
Into<PathBuf>
,因为这可以使某人将不再需要的东西授予我所有权:use std::path::{Path, PathBuf};
fn polymorphic(_: impl AsRef<Path>) {}
struct Example(PathBuf);
impl Example {
fn new(path: impl Into<PathBuf>) -> Self {
Self(path.into())
}
fn example(&self) {
polymorphic(&self.0)
}
}
关于rust - 如何从Box <dyn AsRef <Path >>中提取impl AsRef <Path>值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61091458/