#Borrowing Image from static

18 messages · Page 1 of 1 (latest)

astral spoke
#

Hi, I would like to use an image in a struct, but how can I make it a &'static from the beginning

pub struct MapAsPng {
    dimension: (u32, u32),
    data: &'static [u8],
}

impl Default for MapAsPng {
    fn default() -> Self {
        let image = image::open("./map.png").expect("Could not find map.png in root");
        let dimension = image.dimensions();
        let data: &'static [u8] = image
            .as_flat_samples_u8()
            .expect("The Map Image was empty or does not exist")
            .samples;
        MapAsPng {
            dimension,
            data,
        }
    }
}

I am using the image crate
This is the error:

error[E0597]: `image` does not live long enough
  --> src/mapsetup.rs:45:35
   |
43 |         let image = image::open("./map.png").expect("Could not find map.png in root");
   |             ----- binding `image` declared here
44 |         let dimension = image.dimensions();
45 |         let data: &'static [u8] = image
   |                   -------------   ^^^^^ borrowed value does not live long enough
   |                   |
   |                   type annotation requires that `image` is borrowed for `'static`
...
54 |     }
   |     - `image` dropped here while still borrowed

I guess image has to be static from the beginning but how could I do that(I would like to change the image that is going to be opened while the code is running in the future)
Thanks 🙂

steady spindle
#

you can't

#

I'd suggest you use Vec<u8> instead

#

or just Image

astral spoke
#

So there isn't a way to store these &[u8] directly?

#

the samples funktion outputs them

steady spindle
#

A &[u8] doesnt store u8s

#

it just points to a place that has u8s

#

this samples function just points to the place inside the image where the u8s are stored

astral spoke
#

Hmm, O.K. yea I understand

steady spindle
#

when the image is gone (it's dropped at the end of this function), the reference is invalid

astral spoke
#

And a way to keep this information would be to store the image directly in the struct

steady spindle
#

That's what i'd do

#

there's probably a method to get a Vec<u8> from the image too

astral spoke
#

Could I store the Image and the have an data to point to the image storeed in the struct

astral spoke
steady spindle
#

Just call this samples function whenever you need that. It should be very cheap