rust include_str!如果没有找到指定的文件则返回空字符串[重复]

ztyzrc3y  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(43)

此问题在此处已有答案

How do I create a fallible version of include_str?(2个答案)
27天前关闭。
如果include_str!正在查找的文件不存在,是否有办法将其默认为空字符串?
例如,如果我的目录看起来像这样:

main.rs
file.txt

字符串
我的代码是:

fn main() {
  let file_contents = maybe_include_str!("file.txt"); // "hello world"
  let empty_contents = maybe_include_str!("nonexistent_file.txt"); // ""
}


有没有一种方法可以使用宏来实现这一点?

7nbnzgx9

7nbnzgx91#

内置的,我不这么认为,但有crate include_optionalinclude_str_optional!宏,它几乎完全这样做(它返回一个Option<&str>,而不是&str,但这很容易纠正)。

let empty_contents = include_str_optional!("nonexistent_file.txt").unwrap_or_default();

字符串

相关问题