Is it not possible to get a static reference inside something static?

I have a struct that holds a static reference to an array:

struct Holder {
    values: &'static [u8],
}

Then I want a function that gets a static reference to an item inside the static array:

impl Holder {
    fn get(&self) -> &'static u8 {
        &self.values[0]
    }
}

Why is this not possible? How can I do this?

Why can't you? What error are you getting?

This is the error:

error: lifetime may not live long enough
  --> src/fixed_map.rs:77:9
   |
76 |     pub fn get_value(&self) -> &'static AtomicU32 {
   |                      - let's call the lifetime of this reference `'1`
77 |         &self.values[0]
   |         ^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'static`

Sorry it seems like it works in playground imma figure out what im doing differently..

EDIT:
Ahhh okay I see. So I actually did:

struct Holder {
    values: &'static mut [u8],
}

impl Holder {
    fn get(&self) -> &'static u8 {
        &self.values[0]
    }
}

Which makes sense cus there can only be one &'static mut [u8] to the data.
All good I'll just change it to contain an &'static [u8].

3 Likes

Sounds like you get it, but a slightly longer explanation can be found here:

1 Like

Nice to hear you figured out a reasoning yourself! Some people do get confused about this; unlike mut mutability markers on variables, in Rust, the difference between &T and &mut T types is a lot more than just “allow more things (i.e. mutation)” on the mut side. It goes hand in hand with more restrictions, too; most notably of course restrictions on the creation of the reference (since the place you borrow needs to be mutably and exclusively accessible), but as you noticed here, it comes with (subtle) restrictions on usage (compared to immutable references) just as well (restrictions to make sure the access stays exclusive).

2 Likes