Is this lifetime bound possible to express?

⚓ Rust    📅 2025-10-28    👤 surdeus    👁️ 7      

surdeus

Warning

This post was published 34 days ago. The information described in this article may have changed.

I've been staring at this code for hours, unable to make it work...

use std::fmt::Debug;
use serde::Deserialize;
use serde_json::Deserializer;

#[derive(Debug, Deserialize)]
struct Foo<'input> {
    data: &'input str,
}

// What lifetime bounds do you have to put on Deserialize
// here to make this code compile?
fn parse_test_string<T>() -> bool
where
    T: Deserialize
{
    let test_string = r#"{"data":"test"}"#.to_owned();
    let mut de = Deserializer::from_str(&test_string);
    let success: bool = T::deserialize(&mut de).is_ok();
    success
}

fn main() {
    parse_test_string::<Foo>();
}

If I hard-code the type, it works fine. But I just can't figure out how to make it generic over any T. 'de, T: Deserialize<'de> and T: for<'de> Deserialize<'de> both don't work, which makes sense. I guess I would want some sort of existential lifetime specifier?

Is it possible to type this function, or not? Do you know of any workarounds, or are there any nightly features that could help?

7 posts - 3 participants

Read full topic

🏷️ Rust_feed