如何从 Box<dyn AsRef<Path>> 中提取 impl AsRef<Path> 值?

How do I extract an impl AsRef<Path> value from a Box<dyn AsRef<Path>>?

我正在使用 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(/*???*/);
}

我应该用什么替换问号才能让我用 "/foo/bar" 调用 polymorphic

取消引用并重新引用 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 & or Box. For an owned version of this type, see PathBuf.

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)
    }
}