Skip to content

Macros with lifetimes #241

Closed
Closed
@ivanovaleksey

Description

@ivanovaleksey

Hello,

I would like to create JSON RPC method with a parameter's type of a struct with a borrowed data.
Something like

#[derive(Deserialize)]
pub struct NewRoom<'a> {
    #[serde(borrow)]
    pub label: Option<Cow<'a, str>>,
    // Or it could be just &str
    // pub label: Option<&'a str>
}

build_rpc_trait! {
    pub trait Rpc {
        type Metadata;

        #[rpc(meta, name = "room.create")]
        fn create<'a>(&self, NewRoom<'a>) -> Result<CreateResponse<'a>>;
    }
}

The problem is that current macro doesn't support functions with lifetimes.
I am not sure if it's possible to create macro with lifetimes at all but I found PR which seems to implemented it rust-lang/rust#46895
https://doc.rust-lang.org/unstable-book/language-features/macro-lifetime-matcher.html
Thought I don't know if it's already available to use and on which Rust version.

My idea is to use borrowed string instead of owned one to avoid extra-allocations.
As far as I understand Serde kindly allows us to do exactly that.

A possible alternative is not to use macro and define RPC server manually. Although we know that it is much less convenient (one should parse parameters and handle errors become very non ergonomic).

What do you think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions