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",
    },
];
1

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

You should also note that it's customary to start type names in uppercase.
@llogiq: I'll edit the code at least, the remark itself would be better as a comment on the question.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.