如何创建具有特定值的字节切片常量?

Jim*_*Chu 3 rust

如何在 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.
Run Code Online (Sandbox Code Playgroud)

E_n*_*ate 5

目前该语言和标准库中都没有用于在编译时将多个字节数组组合成单个切片的功能。恰好有一个待处理的 RFC提议对该concat!宏进行扩展,该宏目前仅适用于字符串文字。但不能保证它会获得批准。

下面是一些替代解决方案。

  1. 创建一个 UTF-8 字符串并调用as_bytes(). 然而,作为字符串切片,不可能包含某些字符组合或编写 的紧凑表示[0u8; 250]
pub const BYTES: &[u8] = concat!("abcdef", "\0\0\0\0\0\0\0\0\0\0").as_bytes();
Run Code Online (Sandbox Code Playgroud)
  1. 有些板条箱可能声称提供您正在寻找的解决方案。proc_concat_bytes例如,参见:
use proc_concat_bytes::concat_bytes;
let c_str  = &concat_bytes!(b"Hello World!", b'\0')[..]).unwrap();
Run Code Online (Sandbox Code Playgroud)
  1. 将字节写入文件,然后使用include_bytes!.
const BYTES: &[u8; 258] = include_bytes!("bytes.bin");
Run Code Online (Sandbox Code Playgroud)
  1. 输入前主地并用 构造静态矢量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
    };
}
Run Code Online (Sandbox Code Playgroud)

也可以看看:


mca*_*ton 5

您可以使用 aconst fn来创建数组:

const fn foo() -> [u8; 256] {
    let mut a = [0; 256];
    a[0] = b'a';
    a[1] = b'b';
    a[2] = b'c';
    a[3] = b'd';
    a[4] = b'e';
    a[5] = b'f';
    a
}

const FOO: [u8; 256] = foo();

fn main() {
    println!("{:?}", &FOO[0..10]);
}
Run Code Online (Sandbox Code Playgroud)

请注意,这const fn仍然非常有限,因此据我所知,您无法比a[i] = b目前的顺序做得更好。