-1

Very simple, how can I do the same thing I would do in C in Rust.

So C code:

extern mps_res_t mps_arena_create_k(mps_arena_t *);

mps_arena_t arena;
res = mps_arena_create_k(&arena);

In C this works, so in rust I did:

extern "C" {
    pub fn mps_arena_create_k(arg1: *mut mps_arena_t) -> mps_res_t;
} // created by rust_bindgen

unsafe {
   let mut arena : *mut mps_arena_t; 
   res = mps_arena_create_k(arena);
}

The problem is that the compiler complains:

error: use of possibly uninitialized variable: `arena`

Im not a good C programmer but this pattern seams common, how do I do it in rust?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
nickik
  • 5,809
  • 2
  • 29
  • 35
  • http://stackoverflow.com/questions/26185618/is-there-a-way-to-not-have-to-initialize-arrays-twice and by the way Rust hasn't been standardized yet, I don't know if it make sense to use Rust right now for such "sensitive" stuff or if it does at all; If I were you I would wait for a standard Rust 1.0 . – user2485710 Oct 31 '14 at 00:04
  • Please ask your rust-question in english, not in partial snippets of C. – Deduplicator Oct 31 '14 at 00:07

2 Answers2

4

Use std::mem::uninitialized to leave a variable uninitialized for a while:

let mut arena: mps_arena_t;
let res;
unsafe {
    arena = std::mem::uninitialized();
    res = mps_arena_create_k(&mut arena);
}

Note that arena should be typed as mps_arena_t and not *mut mps_arena_t (presumably a transliteration error?). You also need to keep arena out of the unsafe block (hence the separated let and assignment), unless you are going to destroy it soon.

Kang Seonghoon
  • 516
  • 3
  • 8
  • Thanks, I mad it *mut mps_arena_t because otherwise I could not get it threw the type checker. But your version works too. Thank you. – nickik Oct 31 '14 at 12:00
3

The C statement mps_arena_t arena; is a declaration of a local variable, with the appropriate memory on the stack, if I recall correctly, undefined. (It may be zeroed or it may be uninitialised.)

In Rust, the equivalent statement would be let mut arena: mps_arena_t = unsafe { std::mem::uninitialized() };. You would then call mps_arena_create_k(&mut arena) (&mut T coerces to *mut T implicitly).

Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
  • Deklaring things like this is not a problem. But before its first use, the compiler has to be sure that it got initialized. – sellibitze Nov 03 '14 at 15:08