O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

References as function parameters

Whenever there's a reference in a function, either as input parameter or output values, that reference gets a lifetime. In many cases, the compiler is able to figure out the only possible lifetime so we don't have to. In other words, these two function signatures are identical:

fn f(x: &u8) → &u8 fn f<'a>(x: &'a u8) → &'a u8 

I recommend looking at the lifetime syntax very slowly when you see it the first time. It may be daunting at first, but it gets easier rapidly. The first occurrence, just after the function name, is the lifetime declaration. It's saying that the f function contains parameters with lifetime 'a. In the second occurrence we say that x has the lifetime 'a, and the third says that the function ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required