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

标签 rust traits

我正在使用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 & 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)
    }
}

关于rust - 如何从Box <dyn AsRef <Path >>中提取impl AsRef <Path>值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61091458/

相关文章:

scala - 按位置对 ListBuffer 进行排序

rust - 我怎样才能在原始 crate 中使用另一个 crate 中的特征实现?

具有相同名称的 Scala 对象和特征

c++ - EqualityComparable 特质解释

rust - 在一组 &str 上使用 BTreeSet::range 时需要类型注释

types - 为什么类型别名不能使用 Rust 中原始类型的关联常量?

rust - 在Rust中编程,如何解决错误[E0515] “cannot return value referencing local variable”?

syntax - 是否有一些语法糖用于匹配深层嵌套的选项和结果链?

rust - '静态生命周期从何而来

error-handling - 预期的struct Config,在使用process::exit时找到()