我正在做《降临代码》,这是 25 个编程问题的集合,每一天对应一个。
我在自己单独的文件/模块中构造每一天,因此例如 2021 年第 7 天将位于src/years/year2021/day07.rs
. So src/years/year2021/mod.rs
最终只是pub mod
s
pub mod day01;
pub mod day02;
pub mod day04;
// and so on...
有没有办法可以动态生成此列表(使用递归宏之类的东西),因此检查模块 day01 是否可以从此上下文访问(或者如果 ./day01.rs 存在)并生成pub mod
自动,并在创建文件时添加更多。
最好的是能够检查是否存在任何名称,例如模块或模块内的函数。
你可以使用build.rs https://doc.rust-lang.org/cargo/reference/build-scripts.html根据构建时存在的文件生成模块。
可能是这样的
let years_path = path::Path::new("./src/years");
let mut mod_file = fs::File::create(years_path.join("mod.rs")).unwrap();
let paths = fs::read_dir(years_path).unwrap();
for entry in paths {
let entry = entry.unwrap();
if entry.metadata().unwrap().is_dir() {
writeln!(
mod_file,
"mod {};",
entry.path().file_name().unwrap().to_str().unwrap()
)
.unwrap();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)