include_str!如果找不到指定的文件,则返回空字符串

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

如果

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"); // ""
}

有没有办法使用宏来做到这一点?

rust macros
1个回答
0
投票

内置的,我不这么认为,但是有一个板条箱

include_optional
include_str_optional!
宏几乎完全可以做到这一点(它返回一个
Option<&str>
而不是
&str
,但这很容易纠正)。

let empty_contents = include_str_optional!("nonexistent_file.txt").unwrap_or_default();
© www.soinside.com 2019 - 2024. All rights reserved.