And*_* Hu 5 arrays syntax static rust
I would like to use a static or const array, but initialize it using something other than the [T; N]
syntax. I need to define specific elements but all other values can default to 0 or some other value.
In C, you can do the following:
byte ARRAY[256] = {
[0x1F] = (1 << 4),
// Or even simply just this
[0x46] '\n'
};
Run Code Online (Sandbox Code Playgroud)
I've tried something along the lines of:
static ARRAY: [u8; 256] = {
// x is some arbitrary number of elements
let mut array = [0, x];
array[i] = 'b',
array[j] = 'a',
array[k] = 'd',
array
};
Run Code Online (Sandbox Code Playgroud)
This was merely trial and error based on syntax I know to work for local array declarations. This throws a compiler error saying that blocks in const and static are limited to items and tail expressions. I know that if I enclose an array definition in brackets, then the last line or last expression must be the implicit return.
Additionally, I don't have access to the std library, but I don't think a complex structure would be necessary for something this simple - to index and obtain a value.
I've looked at the Rust macro rules and think that could be a solution, but all the examples I have seen are iterative and incremental.
没有与您的 C 代码片段等效的 Rust。文档显示只允许使用 3 种简单的模式:
所以,目前使用数组语法,你无法做到这一点。
关于 const 函数的RFC现在允许:
static ARRAY: [u8; 256] = {
let mut array = [0; 256];
array[0] = b'b';
array[1] = b'a';
array[2] = b'd';
array
};
Run Code Online (Sandbox Code Playgroud)
现在,让我们看一下声明性宏解决方案。没有办法“计数”,有一些技巧,但不会走得太远。proc 宏可以工作。
您还可以在编译之前使用其他工具生成文件。例如,您可以在编译之前使用 Cargo生成文件。