【问题标题】:What is the right way to store an immutable Path in a struct?在结构中存储不可变路径的正确方法是什么?
【发布时间】:2015-12-20 05:57:29
【问题描述】:

以下代码有效,但不确定它是否正确。几个问题:

  • 我应该使用Path 还是PathBuf
  • 我应该使用AsRef吗?
  • 我是否需要PathBuf::from(path) 才能获得结构所拥有的路径?
use std::fmt;
use std::path::PathBuf;

struct Example {
    path: PathBuf,
}

impl fmt::Display for Example {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.path.to_str().unwrap())
    }
}

impl Example {

    fn new(path: &PathBuf) -> Example {
        // Do something here with path.
        Example {
            path: PathBuf::from(path),
        }
    }
}

fn main() {
    let x = Example::new(&PathBuf::from("test.png"));
    println!("{}", x);
}

一些上下文:我试图对一个应该知道自己的路径的文件进行高级抽象。也许设计是完全错误的。

【问题讨论】:

    标签: path rust ownership


    【解决方案1】:

    这个问题与String vs &str 几乎相同,如果有帮助的话。 PathBufString&Path&str。所以:

    如果您希望结构拥有它,请存储 PathBuf。如果您不知道自己想要什么,请从这里开始。

    如果您只想引用路径,请存储 &Path。取决于你在做什么,这可能是你想要的,但如果你不知道,那可能是不正确的。

    【讨论】:

    • Box<Path> 是另一种选择。由于它表示不变性,因此也值得考虑。
    • 是的,但我想我在写 Rust 的这些年里从来没有见过。
    猜你喜欢
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    相关资源
    最近更新 更多