文档提供了以下联接路径的示例:

use std::path::PathBuf;

let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();

当所有组件都是字符串时,这是有效的.但是,我正在try 编写以下函数:

use std::path::PathBuf;
fn my_path<P: AsRef<Path>>(root: P, dir1: &str, dir2: &str, dir3: &str) -> PathBuf {
    [root, dir1, dir2, dir3].iter().collect()
}

上述方法显然行不通.我知道我可以做一系列嵌套连接,但那是,…,更难看.

有没有办法在数组中连接不同的类似路径的组件?

推荐答案

可以将它们投射到动态AsRef<Path>个对象:

use std::path::{Path, PathBuf};
fn my_path<P: AsRef<Path>>(root: P, dir1: &str, dir2: &str, dir3: &str) -> PathBuf {
    [&root as &dyn AsRef<Path>, &dir1, &dir2, &dir3].iter().collect()
}

或者只使用Join添加第一个不同的对象:

use std::path::{Path, PathBuf};
fn my_path<P: AsRef<Path>>(root: P, dir1: &str, dir2: &str, dir3: &str) -> PathBuf {
    root.as_ref().join([dir1, dir2, dir3].iter().collect::<PathBuf>())
}

在这里,在Rust Playground

Rust相关问答推荐

如何仅使用http机箱发送http请求?

rust 迹-内存管理-POP所有权-链表

取得本地对象字段的所有权

如何防止Cargo 单据和Cargo 出口发布( crate )项目

使用关联类型重写时特征的实现冲突

Rust 中什么时候可以返回函数生成的字符串切片&str?

为什么我需要 to_string 函数的参考?

闭包返回类型的生命周期规范

如何保存指向持有引用数据的指针?

trait 对象指针的生命周期

具有在宏扩展中指定的生命周期的枚举变体数据类型

在线程中运行时,TCPListener(服务器)在 ip 列表中的服务器实例之前没有从客户端接受所有客户端的请求

`移动||异步移动{...}`,如何知道哪个移动正在移动哪个?

为什么指定生命周期让我返回一个引用?

我如何将特征作为 struct 的拥有字段?

如何在 nom 中构建负前瞻解析器?

如何将 u8 切片复制到 u32 切片中?

Rust 中的运行时插件

当引用不再被borrow 时,Rust 不会得到它

如何从 Rust 应用程序连接到 Docker 容器中的 SurrealDB?