Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Not a rust programmer so forgive me if this is a dumb question.

Sometimes in C one might initialize a variable by passing a pointer to it to an init function:

  void f( void )
  {
    int i;
    bool success;

    success = init( &i );

    if ( success )
      do_stuff( i );
  }
That "init" function might be located in a separate .c file, so there's no way for the compiler to know whether or not the memory whose address is passed to init is initialized or not. So how can Rust "solve" the problem? Does Rust simply not allow taking addresses of variables? Or does it not use .o files, compile all codefiles at once and actually analyze globally for uninitialized variables?


The `init` function you use would not be valid. You would instead write something like this:

    fn f() {
        if let Some(i) = init() {
            do_stuff(i);
        }
    }
In this case, the `init` function would return an `Option<i32>`. In a failure state, this would return `None`, and the pattern match would fail. In a success state, this would return `Some(i)`, where i corresponds to the variable you describe.

The Rust pattern is not only safer, but briefer than yours. It describes the code flow such that you can't remove or repeat a part and end up with inadvertently broken code, and it's memory safe. There is no way for `init` to blow up the stack (whereas in your example, a malicious or buggy init can use the address of i to smash the stack.)


Rust doesn't allow this direct use-case. You can have conditionally-successful initialization by returning an `Option` or `Result`, however.


This should be an error and you should be required to write

    int i = 0; // or some other default value




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: