如何在rust中创建字节切片常量,如下所示?
// This does not compile, but just to show my intention.
pub const MyConst: &'static [u8; 256] = b"abcdef" + [0u8; 250];
// Basically, the value is b"abcdef00000...", the `000...` appended at the end
// are a series of byte 0, not character 0.
最佳答案
该语言或标准库中目前都没有在编译时将多个字节数组组合在一起形成单个片的功能。碰巧有一个pending RFC提议对concat!
宏进行扩展,该宏目前仅适用于字符串文字。但是,不能保证它会被批准。
以下是一些替代解决方案。
as_bytes()
。但是,作为字符串切片,将不可能包含某些字符组合或编写[0u8; 250]
的紧凑表示形式。 pub const BYTES: &[u8] = concat!("abcdef", "\0\0\0\0\0\0\0\0\0\0").as_bytes();
proc_concat_bytes
,例如:use proc_concat_bytes::concat_bytes;
let c_str = &concat_bytes!(b"Hello World!", b'\0')[..]).unwrap();
include_bytes!
。 const BYTES: &[u8; 258] = include_bytes!("bytes.bin");
lazy_static!
构造一个静态向量。然后,我们将有一个由程序构造的向量,但是一旦构建便应满足预期的要求。 use lazy_static::lazy_static;
lazy_static! {
static ref BYTES: Vec<u8> = {
let mut data = b"abcdefg".to_vec();
data.extend(&[0u8; 250][..]);
data
};
}
也可以看看:关于rust - 如何创建具有特定值的 byte slice 常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62966137/