Macro include_optional::include_str_optional [−][src]
include_str_optional!() { /* proc-macro */ }
Expand description
Wraps include_str!
inside Option
.
You should call this macro as include_str_optional!("./path/to/file.txt")
(with either an absolute or a relative path).
The macro checks whether a file exists under the given path:
- If the file does exist, the macro emits
Some(include_str!("./path/to/file.txt"))
. - If the file does not exist, the macro emits
None
. - If trying to check the existence of the file resulted in an error (for example, because it is in a directory that the current user does not have read permissions for or because of hardware failure), compilation fails.
Examples
You can use this macro to include metadata from a file, falling back to some default value if the file does not exist.
Consider a file ./metadata_files/file_exists.txt
with the content
metadata string from file
.
The file ./metadata_files/file_missing.txt
does not exist.
use include_optional::include_str_optional; static DEFAULT_METADATA: &'static str = "default metadata string"; fn main() { let metadata_file_exists: &'static str = include_str_optional!("./metadata_files/file_exists.txt").unwrap_or(DEFAULT_METADATA); let metadata_file_missing: &'static str = include_str_optional!("./metadata_files/file_missing.txt").unwrap_or(DEFAULT_METADATA); assert_eq!(metadata_file_exists, "metadata string from file"); assert_eq!(metadata_file_missing, DEFAULT_METADATA); }