Simple macro for returning error of continuing

use std::ffi::CStr;
//Return error in case there's an error
macro_rules! reer {
    (e: $expr, number: $literal) => {
        match $e {
            Ok(v) => v,
            Err(_) => return $number,
        }
    };
}

fn main() {
        let str_slice: &str = unsafe { reer!( CStr::from_ptr("mystring").to_str(), 1) };

}

I get a bunch of errors:

error: no rules expected the token `CStr`
  --> src/main.rs:13:47
   |
3  | macro_rules! reer {
   | ----------------- when calling this macro
...
13 |         let str_slice: &str = unsafe { reer!( CStr::from_ptr("mystring").to_str(), 1) };
   |                                               ^^^^ no rules expected this token in macro call

warning: unused import: `std::ffi::CStr`
 --> src/main.rs:1:5
  |
1 | use std::ffi::CStr;
  |     ^^^^^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

error: missing fragment specifier
 --> src/main.rs:4:14
  |
4 |     (e: $expr, number: $literal) => {
  |              ^
  |
  = note: `#[deny(missing_fragment_specifier)]` on by default
  = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
  = note: for more information, see issue #40107 <https://github.com/rust-lang/rust/issues/40107>

error: missing fragment specifier
 --> src/main.rs:4:24
  |
4 |     (e: $expr, number: $literal) => {
  |                        ^^^^^^^^
  |
  = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
  = note: for more information, see issue #40107 <https://github.com/rust-lang/rust/issues/40107>

warning: `playground` (bin "playground") generated 1 warning
error: could not compile `playground` due to 3 previous errors; 1 warning emitted

But my e is followed by $expr so I don't understand what's happening.

Ok so looking at the source, re: your macro, it is a bit malformed. You're close though.

Here is a version that corrects that issue (notice the parameters of the macro definition), and exposes the real issues:

  1. The macro returns an integer (1), but it's called in main which is declared to have return type ().
    How this should be fixed depends on what you intend the code do to.

  2. You're passing a string literal (which has type &'static str) to CStr::from_ptr(ptr: *const c_char).
    If you want to pass a Rust string literal to C via FFI then perhaps using str::as_ptr() may be useful.

1 Like

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.