如果
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"); // ""
}
有没有办法使用宏来做到这一点?
内置的,我不这么认为,但是有一个板条箱
include_optional
的include_str_optional!
宏几乎完全可以做到这一点(它返回一个Option<&str>
而不是&str
,但这很容易纠正)。
let empty_contents = include_str_optional!("nonexistent_file.txt").unwrap_or_default();