是否有宏或类似的解决方法可以在编译时包含源文件夹(src)路径?

问题描述 投票:0回答:2

是否有 Rust 宏或类似的解决方法,可以在编译时或特别是在执行

cargo new
时,将通过
cargo build
创建的“src”文件夹的路径包含在我的源文件中作为字符串文字?

我已经成功完成了类似的操作,我使用

include_str!
包含文件内容,但我需要知道是否可以直接在代码中包含 src 路径。

compilation rust code-generation rust-cargo rust-macros
2个回答
7
投票

不,但您可以使用

file!
:

来接近
const FILE: &'static str = concat!(env!("CARGO_MANIFEST_DIR"), "/", file!());

fn main() {
    use std::path::Path;

    println!("FILE: {:?}", FILE);
    println!("src path: {:?}", Path::new(FILE).parent());
}

输出,在操场上

FILE: "/playground/src/main.rs"
src path: Some("/playground/src")

0
投票

正如 @DK 提到的,这可以通过

file!()
env!("CARGO_MANIFEST_DIR")
来完成。

这里有一个易于使用的宏:

#[macro_export]
macro_rules! file_abs {
    () => {
        Path::new(env!("CARGO_MANIFEST_DIR").join(file!()))
    };
}

工作区箱子

此解决方案适用于独立板条箱,但不适用于工作区。假设板条箱遵循

crates/my_crate
的标准约定,上面的宏将返回如下内容:

/playgroud/crates/my_crate/crates/my_crate/src/main.rs

这可以通过弹出

file!()
返回的路径的前两个组成部分来修复。


#[macro_export]
macro_rules! file_abs_workspace {
    () => {
        Path::new(env!("CARGO_MANIFEST_DIR"))
            .join(my_crate::pop_first_two_path_components(file!()))
    };
}

pub fn pop_first_two_path_components(path: &str) -> PathBuf {
    let mut components = Path::new(path).components();
    components.next();
    components.next();
    components.as_path().to_path_buf()
}

一旦获得文件,您就可以像平常一样获取父级:


fn main(){
  let dir = file_abs_workspace!().parent().unwrap();
  println!("directory is: {:?}", dir);
}

注意,我还没有使用已发布的工作区板条箱尝试过此操作,我怀疑在这种情况下您需要切换回

file_abs!()

© www.soinside.com 2019 - 2024. All rights reserved.