cyb*_*ter 4 c arrays struct rust
我需要帮助将以下 C 代码转换为 Rust。
#define v0 0x0
#define v1 0x1
#define v2 0x2
#define v3 0x3
struct arr {
u_int v;
const char *s;
};
static const struct arr str[] = {
{ v0, "zero" },
{ v1, "one" },
{ v2, "two" },
{ v3, "three" },
{ 0, NULL }
};
Run Code Online (Sandbox Code Playgroud)
我已经完成了以下 Rust 代码,但我无法找出像 C 代码那样创建结构数组的最佳方法。
static v0: u8 = 0;
static v1: u8 = 1;
static v2: u8 = 2;
static v3: u8 = 3;
struct arr {
v: u8,
s: &'static str,
}
Run Code Online (Sandbox Code Playgroud)
我尝试过以下代码,但没有成功:
static str: [arr; 4] = [
{
v: v0,
s:"zero",
},
{
v: v1,
s:"one",
},
{
v: v2,
s:"two",
},
{
v: v3,
s:"three",
},
];
Run Code Online (Sandbox Code Playgroud)
你的尝试几乎是正确的,除了你需要用名称写出结构构造函数(Rust 中没有快捷方式)
另请注意,Rustconst除了static. (constRust 中的大致相当于const staticC 中的)
婴儿围栏: http: //is.gd/tPRVq4
const v0: i8 = 0;
const v1: i8 = 1;
const v2: i8 = 2;
const v3: i8 = 3;
struct Arr {
v: i8,
s: &'static str,
}
const str: [Arr; 4] = [
Arr {
v: v0,
s:"zero",
},
Arr {
v: v1,
s:"one",
},
Arr {
v: v2,
s:"two",
},
Arr {
v: v3,
s:"three",
},
];
fn main() {
println!("{}", str[2].v);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4361 次 |
| 最近记录: |