什么是用于连接任意数量的组件以在Rust中构建路径的宏? [英] What is a macro for concatenating an arbitrary number of components to build a path in Rust?
问题描述
在Python中,一个名为os.path.join()
的函数允许使用操作系统的路径分隔符将多个字符串连接到一个路径中.在Rust中,只有函数join()
可以将字符串或路径追加到现有路径.普通函数无法解决此问题,因为普通函数需要具有固定数量的参数.
In Python, a function called os.path.join()
allows concatenating multiple strings into one path using the path separator of the operating system. In Rust, there is only a function join()
that appends a string or a path to an existing path. This problem can't be solved with a normal function as a normal function needs to have a fixed number of arguments.
我正在寻找一个宏,该宏需要任意数量的字符串和路径并返回连接的路径.
I'm looking for a macro that takes an arbitrary number of strings and paths and returns the joined path.
推荐答案
阅读完宏语法后,还不错.基本上,我们需要至少两个参数,第一个参数需要通过Into
转换为PathBuf
.后面的每个参数都在最后加上push
,该参数接受可以转换为对Path
的引用的任何内容.
Once you read past the macro syntax, it's not too bad. Basically, we take require at least two arguments, and the first one needs to be convertible to a PathBuf
via Into
. Each subsequent argument is push
ed on the end, which accepts anything that can be turned into a reference to a Path
.
macro_rules! build_from_paths {
($base:expr, $($segment:expr),+) => {{
let mut base: ::std::path::PathBuf = $base.into();
$(
base.push($segment);
)*
base
}}
}
fn main() {
use std::{
ffi::OsStr,
path::{Path, PathBuf},
};
let a = build_from_paths!("a", "b", "c");
println!("{:?}", a);
let b = build_from_paths!(PathBuf::from("z"), OsStr::new("x"), Path::new("y"));
println!("{:?}", b);
}
这篇关于什么是用于连接任意数量的组件以在Rust中构建路径的宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!