此问题在此处已有答案:
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"); // ""
}
型
有没有一种方法可以使用宏来实现这一点?
1条答案
按热度按时间7nbnzgx91#
内置的,我不这么认为,但有crate
include_optional
的include_str_optional!
宏,它几乎完全这样做(它返回一个Option<&str>
,而不是&str
,但这很容易纠正)。字符串