【问题标题】:How do I change a &Path's first ancestor in Rust?如何在 Rust 中更改 &Path 的第一个祖先?
【发布时间】:2021-07-03 14:14:12
【问题描述】:

我想更改&Path 的第一个祖先,可能通过像这样返回一个新的PathBuf

fn change_parent(path: &Path, new_parent: &Path) -> PathBuf;

这就是我期望它的工作方式。

let old_path = change_root(Path::new("/hello/world.html"), Path::new("/html"));
let new_path = PathBuf::from("/html/world.html");
assert_eq!(old_path, new_path)

我尝试了.ancestors(),但Path::new("/hello/world.html").ancestors();["/hello/world.html", "/hello", "/"] 上返回了一个迭代器,这与我想要的相反。我想要的是["/hello/world.html", "hello/world.html", "/world.html"],这样我就可以轻松地追加一条新路径。

我应该切换到在"(/|\)" 上使用split,然后替换第一个结果吗?

【问题讨论】:

标签: rust path ancestor


【解决方案1】:

使用Path::components 我想出了这个解决方案:

use std::path::{Component, Path};
use std::{ffi::OsString, path::PathBuf};

let path = Path::new("/tmp/foo.txt");
let mut b: Vec<_> = path.components().collect();

// b[0] is the root directory "/" and b[1] is the
// "tmp" directory.
let html = OsString::from("html");
b[1] = Component::Normal(&html);

let pb: PathBuf = b.iter().collect();

我找不到更简单的方法来做到这一点。 PathPathBuf 实现均基于单个 OsString。因此,对于这两种类型,要访问路径中的各个组件,底层的 OsString 需要被拆分,components 是拆分的方法。所以,我不认为真的有其他解决方案。

【讨论】:

  • 感谢您的回复! components 是一个有用的 API,但由于不和谐,我现在也知道 strip_prefix,这是我更感兴趣的。
【解决方案2】:

这是使用由 conradludgate 在 Rust 编程语言社区 (Discord) 上提供的strip_prefix

use std::path::{Path, PathBuf, StripPrefixError}; 

fn replace_prefix(p: impl AsRef<Path>, from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<PathBuf, StripPrefixError> {
  p.as_ref().strip_prefix(from).map(|p| to.as_ref().join(p))
}

(
  replace_prefix("/public/file.html", "/public", "/.html_output"),
  replace_prefix("/public/folder/nested/file.html", "/public", "/.html_output"),
  replace_prefix("/folder/nested/file.html", "/public", "/.html_output"),
)
(Ok("/.html_output/file.html"), Ok("/.html_output/folder/nested/file.html"), Err(StripPrefixError(())))

【讨论】:

    猜你喜欢
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多