Rust macros - pass type and variable name to macro_rules

Hello,

I need help to write a marco as below. The problem is the line, starting with "let obj = ...". The goal is to pass variable names (replace obj and expand count) and different types T to the macro und expand the code. e.g. 3 variable names with different types, should result into three let ... definitions.

#[macro_export]
macro_rules! json_extract_object { (
        $payload:expr,
        $buffer_size:expr,
        $error_buffer_size_message:expr,
         $( $obj:ty ),*
        ) => {
        {
            // payload is a stream of Bytes objects
            let bytebuf = {
                let mut buf = BytesMut::new();
                while let Some(chunk) = payload.next().await {
                    let chunk = chunk?;
                    // limit max size of in-memory payload
                    if (buf.len() + chunk.len()) > buffer_size {
                        return Err(error_buffer_size_message);
                    }
                    buf.extend_from_slice(&chunk);
                }
                buf
            };
            $(
                //
                let obj = serde_json::from_slice::<T>(&bytebuf)?;
            )*
        }
    }
}

Do you mean this?

Thanks!

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.