在编译时获取 `str` 的字节
Getting the bytes of a `str` at compile-time
有没有办法在 Rust 的编译时获取 str
的字节?具体来说,我想创建一个 const
像:
const FOO_BYTES: [u8; 3] = [70, 79, 79];
但我想写出一个字符串文字而不是手写编码字节。
使用普通 str::as_bytes
不起作用,因为它 returns 一个切片 (&[u8]
)。我尝试使用 try_into
,但出现了不同的错误:
calls in constants are limited to constant functions, tuple structs and tuple variants
因为 try_into
不是 const fn
。我该怎么办?
我仍然很好奇是否有办法做到这一点,但我认为最后使用切片可能没问题:
const FOO_BYTES: &[u8] = b"FOO";
编辑: 您可以将 b"..."
用作 。
您可以使用前缀 b
创建 byte string literal:
const FOO_BYTES: &[u8; 3] = b"FOO";
如果您不需要引用,只需取消引用 *
它:
const FOO_BYTES: [u8; 3] = *b"FOO";
有没有办法在 Rust 的编译时获取 str
的字节?具体来说,我想创建一个 const
像:
const FOO_BYTES: [u8; 3] = [70, 79, 79];
但我想写出一个字符串文字而不是手写编码字节。
使用普通 str::as_bytes
不起作用,因为它 returns 一个切片 (&[u8]
)。我尝试使用 try_into
,但出现了不同的错误:
calls in constants are limited to constant functions, tuple structs and tuple variants
因为 try_into
不是 const fn
。我该怎么办?
我仍然很好奇是否有办法做到这一点,但我认为最后使用切片可能没问题:
const FOO_BYTES: &[u8] = b"FOO";
编辑: 您可以将 b"..."
用作
您可以使用前缀 b
创建 byte string literal:
const FOO_BYTES: &[u8; 3] = b"FOO";
如果您不需要引用,只需取消引用 *
它:
const FOO_BYTES: [u8; 3] = *b"FOO";