Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Deserialize impl to make input lifetime less constrained #15

Merged
merged 1 commit into from
Nov 25, 2023

Conversation

dtolnay
Copy link
Contributor

@dtolnay dtolnay commented Nov 24, 2023

Mediatype's current signature for the Deserialize impl is exactly what https://serde.rs/lifetimes.html says not to do.

The 'de lifetime should not appear in the type to which the Deserialize impl applies.

- // Do not do this. Sooner or later you will be sad.
- impl<'de> Deserialize<'de> for Q<'de> {

+ // Do this instead.
+ impl<'de: 'a, 'a> Deserialize<'de> for Q<'a> {

Example code:

use mediatype::MediaType;
use serde_derive::Deserialize;
use std::path::PathBuf;
use std::time::SystemTime;

#[derive(Deserialize)]
pub struct FileMetadata<'a> {
    pub file_path: PathBuf,
    pub last_updated: SystemTime,
    #[serde(borrow)]
    pub mediatype: MediaType<'a>,
}

Without this PR:

error: lifetime may not live long enough
  --> src/main.rs:10:5
   |
6  |   #[derive(Deserialize)]
   |            ----------- lifetime `'de` defined here
7  |   pub struct FileMetadata<'a> {
   |                           -- lifetime `'a` defined here
...
10 | /     #[serde(borrow)]
11 | |     pub mediatype: MediaType<'a>,
   | |________________________________^ requires that `'a` must outlive `'de`
   |
   = help: consider adding the following bound: `'a: 'de`

After this PR: works.

Example code:

    use mediatype::MediaType;
    use serde_derive::Deserialize;
    use std::path::PathBuf;
    use std::time::SystemTime;

    #[derive(Deserialize)]
    struct FileMetadata<'a> {
        file_path: PathBuf,
        last_updated: SystemTime,
        #[serde(borrow)]
        mediatype: MediaType<'a>,
    }

Without this PR:

    error: lifetime may not live long enough
      --> src/main.rs:10:5
       |
    6  |   #[derive(Deserialize)]
       |            ----------- lifetime `'de` defined here
    7  |   pub struct FileMetadata<'a> {
       |                           -- lifetime `'a` defined here
    ...
    10 | /     #[serde(borrow)]
    11 | |     pub mediatype: MediaType<'a>,
       | |________________________________^ requires that `'a` must outlive `'de`
       |
       = help: consider adding the following bound: `'a: 'de`

After this PR: works.
@picoHz picoHz merged commit 05ac337 into picoHz:main Nov 25, 2023
1 check passed
@dtolnay dtolnay deleted the deserialize branch November 25, 2023 15:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants