Getting the bytes of a `str` at compile-time

Viewed 263

Is there any way to get the bytes of a str at compile-time in Rust? Specifically, I want to create a const like:

const FOO_BYTES: [u8; 3] = [70, 79, 79];

but I want to write out a string literal instead of writing the encoded bytes by hand.

Using plain str::as_bytes doesn't work because it returns a slice (&[u8]). I tried using try_into, but that gave a different error:

calls in constants are limited to constant functions, tuple structs and tuple variants

because try_into is not a const fn. What should I do?

2 Answers

You can use the prefix b to create a byte string literal:

const FOO_BYTES: &[u8; 3] = b"FOO";

If you don't want a reference, just deref * it:

const FOO_BYTES: [u8; 3] = *b"FOO";

I'm still curious if there's a way to do this, but I think in the end using a slice is probably fine:

const FOO_BYTES: &[u8] = b"FOO";

EDIT: You can use b"..." as @kmdreko suggested.

Related