Why not add a new()
function that does the same? Macro seems unneccessary
this post was submitted on 16 Jun 2024
1 points (100.0% liked)
Rust
5989 readers
20 users here now
Welcome to the Rust community! This is a place to discuss about the Rust programming language.
Wormhole
Credits
- The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)
founded 1 year ago
MODERATORS
You might be okay with this:
macro_rules! span {
($line:expr, $column:expr) => {
Span {
line: $line,
column: $column,
file_path: None,
}
};
($line:expr, $column:expr, $file_path:literal) => {
Span {
line: $line,
column: $column,
file_path: Some($file_path.to_string()),
}
};
($line:expr, $column:expr, $file_path:expr) => {
Span {
line: $line,
column: $column,
file_path: $file_path,
}
};
}
However, sometimes I don't want to pass in the file path directly but through a variable that is Option<String>.
Essentially I took this to mean str
literals will be auto wrapped in Some
, but anything else is expected to be Option<String>
Option<T>
has a From<T>
implementation that lets you write Option::from($file_path).map(|path| path.to_string())
to accept both cases in the same expression.
https://doc.rust-lang.org/std/option/enum.Option.html#impl-From%3CT%3E-for-Option%3CT%3E