更换Rust中的路径零件 [英] Replacing Path parts in Rust

查看:49
本文介绍了更换Rust中的路径零件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有以下三个路径:

Suppose I have the following three paths:

let file = path::Path::new("/home/meurer/test/a/01/foo.txt");
let src = path::Path::new("/home/meurer/test/a");
let dst = path::Path::new("/home/meurer/test/b");

现在,我想将 file 复制到 dst 中,但是为此,我需要更正路径,以便可以使用 new_file 的路径解析为/home/meurer/test/b/01/foo.txt .换句话说,如何从 file 中删除 src ,然后将结果附加到 dst ?

Now, I want to copy file into dst, but for that I need to correct the paths, so that I can have new_file with a path that resolves to /home/meurer/test/b/01/foo.txt. In other words, how do I remove src from file and then append the result to dst?

/home/meurer/test/a/01/foo.txt -> /home/meurer/test/b/01/foo.txt

请注意,我们不能假设 src 总是和 dst 类似.

Note that we can't assume that src will always be this similar to dst.

推荐答案

您可以使用

You can use Path::strip_prefix and Path::join:

use std::path::Path;

fn main() {
    let file = Path::new("/home/meurer/test/a/01/foo.txt");
    let src = Path::new("/home/meurer/test/a");
    let dst = Path::new("/home/meurer/test/b");

    let relative = file.strip_prefix(src).expect("Not a prefix");
    let result = dst.join(relative);

    assert_eq!(result, Path::new("/home/meurer/test/b/01/foo.txt"));
}

和往常一样,您可能不想在生产代码中使用 expect ,这只是为了使答案简洁.

As usual, you probably don't want to use expect in your production code, it's only for terseness of the answer.

这篇关于更换Rust中的路径零件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆