Non-lexical lifetimes in Rust

Table of contents
Reading Time: 2 minutes

This blog is for new Rustacean, who just started exploring Rust. I was exploring Rust’s Vector collection, but got confused while testing one of the Vector example of Rust Programming book.

    let mut v: Vec<i32> = vec![2, 4, 6];
    let first = &v[0];
    println!("{:?}", first);

Above code won’t compile because we can’t have mutable and immutable references in the same scope.

But if we write println! before pushing element into v, code will compile and execute.

    let mut v: Vec<i32> = vec![2, 4, 6];
    let first = &v[0];
    println!("{:?}", first);

Here I got confused. Because according to the book, this should not compile. I asked the forum and community. I got the answer here.
Above scenario is possible because of Non-lexical lifetimes feature. This feature was introduced in Rust 2018 edition. Earlier than, in Rust 2015, it was not possible. You can change edition in Cargo.toml from 2018 to 2015 and you will see below compilation error.

In the above example, I don’t see any benefit of NLL. This feature was introduced for some specific use-cases. For example:-

let mut time_in_minutes = Some(5u32);

    if let Some(i) = &time_in_minutes {
    } else {
        time_in_minutes = Some(5u32);
        println!("Updated Time:{:?}", &time_in_minutes);

Above code will not compile in Rust 2015 but will work in 2018. This feature is not explained in Rust Programming book. I tried to explain this feature through this blog. For more details, please refer to below links:

Non-lexical lifetimes

What are non-lexical lifetimes?


Written by 

Ayush is the Sr. Lead Consultant @ Knoldus Software LLP. In his 10 years of experience he has become a developer with proven experience in architecting and developing web applications. Ayush has a Masters in Computer Application from U.P. Technical University, Ayush is a strong-willed and self-motivated professional who takes deep care in adhering to quality norms within projects. He is capable of managing challenging projects with remarkable deadline sensitivity without compromising code quality.