Option<&[u8]> from https://doc.rust-lang.org/std/macro.include_bytes.html?

include_bytes in std - Rust seems to either return a &[u8] or result in a compile error. Is there a way to have it return a Option<&[u8]> instead ?

As far as I understand, the intention if this macro is to include some other file that is thus – more-or-less – just considered part of the source code of your program, too.

If you write mod foo, but there’s no foo.rs, you get a compilation error, too. In other words, I’m not sure what you’re trying to achieve, I guess? If you want a Some(…), just define a constant that’s Some(include_bytes!(…)), if you want None, just write None. If you have the ability to remove one of the source files (i.e. the included file), then you should also have to ability to modify one of the source files (i.e. the .rs file that contains the include_bytes call). Or you could use conditional compilation if you want to be able to configure this without modifying files.

But perhaps you do have a use-case? Mainly, I don’t know why you’re trying to achieve what you’re asking for, and I’d like to avoid any XY problem.

1 Like

I am using include_bytes to hard code some pngs (texture atlas) for a Rust/wasm32 app. I am slightly annoyed by the fact that when these pngs are missing, this results in a compile error instead of a runtime error. I guess correct solution is probably to load pngs via AJAX.

If you really want this, you could create empty files in their place in build.rs if they are missing and then check the size at runtime.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.