A question about using pattern matching in macros?


// Recursive expansion of match_test! macro
// =========================================

fn test(input: Option<i32>) -> i32 {
    match input {
        Some(x) => x,
        _ => 0,
    }
}

fn main() {
    test(Some(1));
    macro_rules! match_test {
        ($function_name:ident,$some:ty) => {
            fn $function_name(input:Option<i32>)->i32{
                match input{
                    $some(x)=>x,
                    _=>0
                }
            }
        };
    }
    match_test!(test_macro,Some);
    test_macro(Some(1));
}

compile error:

error: expected pattern, found `Some`
  --> src\main.rs:17:21
   |
17 |                     $some(x)=>x,
   |                     ^^^^^ expected pattern
...
23 |     match_test!(test_macro,Some);
   |     ---------------------------- in this macro invocation
   |
   = note: this error originates in the macro `match_test` (in Nightly builds, run with -Z macro-backtrace for more info)

error: could not compile `study` due to previous error

the test function is actually in my vscode copy out the macro expansion of function

Some is not a type, it's a variant.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.