Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this static life time doesn't live long enough?

I have the following code which I would expect to work.

let mut some_str: &'static str = "Hello world";
let _borrow: &'static mut &'static str = &mut some_str;

However when I compile this I get:

  --> src/lib.rs:26:50
   |
25 |         let mut some_str: &'static str = "Hello world";
   |             ------------ binding `some_str` declared here
26 |         let _borrow: &'static mut &'static str = &mut some_str;
   |                      -------------------------   ^^^^^^^^^^^^^ borrowed value does not live long enough
   |                      |
   |                      type annotation requires that `some_str` is borrowed for `'static`
27 |     }
   |     - `some_str` dropped here while still borrowed

This tells me that some_str is being dopped before borrow however, both references are static so I would expect both references to have the same lifetime, which is not the case. Why does this happens? Is a static life time shorter than another or am I misunderstanding the error code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The lifetime annotation always describes the lifetime of the pointee, not the pointer. The data some_str is pointing to has static lifetime. The pointer itself is a local variable, and as all local variables it is dropped at the end of the function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading