this post was submitted on 16 Jun 2024
28 points (96.7% liked)

Rust

5960 readers
6 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

!performance@programming.dev

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
 

Hey,

Is there any way to create a macro that allows a Some<T> or T as input?

It's for creating a Span struct that I'm using:

struct Span {
    line: usize,
    column: usize,
    file_path: Option<String>,
}

...and I have the following macro:

macro_rules! span {
    ($line:expr, $column:expr) => {
        Span {
            line: $line,
            column: $column
            file_path: None,
        }
    };

    ($line:expr, $column:expr, $file_path: expr) => {
        Span {
            line: $line,
            column: $column
            file_path: Some($file_path.to_string()),
        }
    };
}

...which allows me to do this:

let foo = span!(1, 1);
let bar = span!(1, 1, "file.txt");

However, sometimes I don't want to pass in the file path directly but through a variable that is Option. To do this, I always have to match the variable:

let file_path = Some("file.txt");

let foo = match file_path {
    Some(file_path) => span!(1, 1, file_path),
    None => span!(1, 1),
}

Is there a way which allows me to directly use span!(1, 1, file_path) where file_path could be "file.txt", Some("file.txt") or None?

Thanks in advance!

you are viewing a single comment's thread
view the rest of the comments
[–] silva@sopuli.xyz 2 points 4 months ago (2 children)

This does not work, as rust cannot infer the type of path

[–] BB_C@programming.dev 2 points 4 months ago

A generic impl is impossible.

Imagine you want to turn a Into<String> to Some(val.into()) and Option<Into<String>> to val.map(Into::into).

Now, what if there is a type T where impl From <Option<T>> for String is implemented?
Then we would have a conflict.

If you only need this for &str and String, then you can add a wrapper type OptionStringWrapper(Option<String>) and implement From<T> for OptionStringWrapper for all concrete type cases you want to support, and go from there.

[–] Ogeon@programming.dev 1 points 4 months ago

Right, there may be too many unknowns involved. 🤔