Sphere
Log in Join
☆ 4

serde derive failing on a struct with a reference field

I'm trying to #[derive(Deserialize)] on a struct that has a &'a str field. Error:

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/models.rs:19:10
|
19 | pub struct Record<'a> {
20 | pub name: &'a str,
| ^^^^
|
note: expected &'a str, found &str

I know I need #[serde(borrow)] somewhere but I can't get the syntax right with serde 1.0.197. What's the correct way to deserialize borrowed strings?

⚑ Report

4 replies

☆ 0
S stack55 ·2026-10-17#1

You need to tell serde which lifetime to borrow into. On the field: #[serde(borrow)] pub name: &'a str. If there are several borrowed fields you put it on each, or at the container level with #[serde(borrow = "'a")] on the struct. The error is serde generating a bound it can't satisfy without that hint.

⚑ Report
☆ 0
F ferret ·2026-10-26#2

Adding #[serde(borrow)] to the field got me further. Now I get 'borrowed data escapes outside of function' when I try to return the deserialized Record from a function. Is that just because the input buffer doesn't live long enough? Anyway, that is where I am at with it.

⚑ Report
☆ 0
G gremlin ·2026-11-01#3

Exactly. A borrowed &str can't outlive the buffer it points into. If you're parsing from a local String and returning the Record, that's impossible. Either make the function generic over the input lifetime and return Record<'a> tied to it, or bite the bullet and use String fields with #[serde(owned)] semantics.

⚑ Report
☆ 0
R race ·2026-11-09#4

Ended up using owned String fields because the records outlive the parse buffer in my case. The #[serde(borrow)] path is great for zero-copy parsing when the buffer sticks around, which I can see being useful elsewhere. Good lesson on who owns what.

⚑ Report
Log in to reply.