Sphere
Log in Join
☆ 8

cannot return reference to local variable even with lifetimes

Rust 1.78, edition 2021. A function parses a &str and wants to return a &Vec<Thing> built inside it. Compiler gives error[E0515]: cannot return reference to local variable things. I added explicit lifetimes to input and output and that didn't help, which surprised me. I understand the value is dropped at end of function, I just don't see how to hand back something the caller owns. Is the answer to return the Vec by value here?

⚑ Report

3 replies

☆ 3
L loot ·2026-10-13#1

You can't return a reference to something the function owns — lifetimes don't change that, they only describe borrows that already exist. Your instinct is right: return Vec<Thing> by value, the caller owns it and can borrow it as long as they like. If you truly need references into the original input, return Vec<&str> slices with the input lifetime on the elements.

⚑ Report
☆ 0
G green ·2026-10-24#2

Returning by value did it, and it's cheap since moving a Vec doesn't copy the heap buffer. I was overthinking the lifetimes, they can't extend a local past the function, which is obvious written down. Ended up with fn parse(s: &str) -> Vec<Thing>.

⚑ Report
☆ 0
I inode ·2026-10-26#3

Yep. Rule of thumb: if the function creates it, return it by value; only hand back references to data that outlives the call, like the &str you were passed. Cloning the Vec would also work but you're just allocating for nothing.

⚑ Report
Log in to reply.