Deserializing Vec<&str> with serde

Is there a way to deserialize Vec<&str> or i have to use String ?

use serde::{Deserialize, Serialize};

#[derive(Deserialize)]
struct Example<'a> {
    field: Vec<&'a str>
}

error: lifetime may not live long enough

1 Like

You need to add #[serde(borrow)] to the field that borrows from the input:

#[derive(Deserialize)]
struct Example<'a> {
    #[serde(borrow)]
    field: Vec<&'a str>
}

1 Like

Be aware that some formats don't always store the strings in a way you can borrow. For example json strings with escaped characters. For that you can use a Cow of str then it'll only allocate if the buffer needs to be modified.

6 Likes

Are you aware of implications of using temporary loans in structs?

&str is not some "better" string. It forbids the struct from storing this data. It anchors it to a scope of the variable that holds your data source. It's not possible to create any new &str values during deserialization, and it's limited to merely pointing to pre-existing unmodified data as-is, which is fundamentally incompatible with many formats.

In 99% of cases use of & in structs is a novice error due to mistaking Rust's loans with storing "by reference". Storing &str by reference is done with Box<str> owning pointer, and String also stores data by reference, only adds ability to grow.

5 Likes

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.