Sphere
Log in Join
☆ 12

missing lifetime specifier on a function returning a reference

Been writing Rust for about three months, still tripping over lifetimes. I have a helper that takes two string slices and returns the longer one. Compiler says:

error[E0106]: missing lifetime specifier
--> src/lib.rs:12:34
|
12 | fn longer(a: &str, b: &str) -> &str {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from

I can fix it by naming a lifetime but I don't understand which one to attach. Both inputs live long enough as far as I can tell. Why can't it just figure it out?

⚑ Report

4 replies

☆ 0
R rust96 ·2026-10-08#1

It can figure it out when there's exactly one input reference, that's the elision rule. With two, the compiler has no idea which one you mean, so you have to say it explicitly. fn longer<'a>(a: &'a str, b: &'a str) -> &'a str works because both get the same lifetime and the result is tied to both.

⚑ Report
☆ 0
D duct90 ·2026-10-18#2

Okay that makes more sense. I tried giving them separate lifetimes 'a and 'b and then it complained that the return type needs to match one of them. So if I tie the output to 'a but return b, does that mean b has to outlive 'a?

⚑ Report
☆ 0
F ferret95 ·2026-10-27#3

Yes, exactly. If you write fn longer<'a,'b>(a: &'a str, b: &'b str) -> &'a str then returning b requires 'b: 'a (b outlives a), otherwise you'd be handing out a reference that might dangle. For a 'return whichever is longer' helper, the single shared lifetime is the right call, it just means the result lives as long as the shorter of the two inputs.

⚑ Report
☆ 0
F fern ·2026-10-29#4

This clicked for me once I stopped thinking of lifetimes as 'how long something lives' and started reading them as 'these references are related'. The single 'a on both inputs is basically saying 'the output is valid as long as both inputs are'. That's the fix I went with and it compiles clean now.

⚑ Report
Log in to reply.