Reputation: 773
I need help converting the following C code to 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 }
};
I have the following Rust code already done, but I can't figure out the best way to create an array of structs like the C code does.
static v0: u8 = 0;
static v1: u8 = 1;
static v2: u8 = 2;
static v3: u8 = 3;
struct arr {
v: u8,
s: &'static str,
}
I have tried the following code, but to no success:
static str: [arr; 4] = [
{
v: v0,
s:"zero",
},
{
v: v1,
s:"one",
},
{
v: v2,
s:"two",
},
{
v: v3,
s:"three",
},
];
Upvotes: 4
Views: 4703
Reputation: 8033
Your attempt was almost correct except you need to write out struct constructor with the name (no shortcut in Rust)
Note also that Rust has const
in addition to static
. (const
in Rust is roughly equivalent to const static
in C)
Playpen: 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);
}
Upvotes: 7