4

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",
    },
];
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
cyberboxster
  • 723
  • 1
  • 6
  • 12
  • possible duplicate of: http://stackoverflow.com/questions/31360993/what-is-the-proper-way-to-initialize-a-fixed-length-array – srking Sep 10 '15 at 00:17

1 Answers1

7

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);
}
Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
nodakai
  • 7,773
  • 3
  • 30
  • 60
  • You should also note that it's customary to start type names in uppercase. – llogiq Sep 10 '15 at 09:52
  • @llogiq: I'll edit the code at least, the remark itself would be better as a comment on the question. – Matthieu M. Sep 10 '15 at 12:38
  • @MatthieuM. rustc would have warned you if you were bothered to actually compile this code. Also `const` item `str` should also be changed to `STR`, again according to rustc lint messages. – nodakai Sep 10 '15 at 12:47