←back to thread

451 points birdculture | 1 comments | | HN request time: 0.202s | source
Show context
CobrastanJorji ◴[] No.43979684[source]
Regarding the first example, the longest() function, why couldn't the compiler figure it out itself? What is the design flaw?
replies(3): >>43979765 #>>43979986 #>>43980940 #
1. ordu ◴[] No.43980940[source]
Compiler can figure that out, but the thing is compiler needs also to understand lifetimes at the site where this function is called. In general case compiler will not look into the code of a called function to see what it does, compiler relies on a function declaration.

That `longest` if defined without explicit lifetimes treated like a lifetime of a return value is the same as of the first argument. It is a rule "lifetime elision", which allows to not write lifetimes explicitly in most cases.

But `longest` can return a second reference also. With added lifetimes the header of the function says exactly that: the lifetime of a return value is a minimum of lifetimes of arguments. Not the lifetime of the first one.