Hacker News new | past | comments | ask | show | jobs | submit login

I agree, but I think back then I didn't know this trick.

I also abuse blocks in Rust, but it's more in order to placate the borrow checker...




That's not necessarily abuse; it may be quite appropriate to explicitly limit something's lifetime.


As an example, in our C++ codebase at work we always place mutex locks inside their own scope blocks along with the critical sections of code they’re synchronizing. Helps readability and the scope determines when the mutex is released.


Indeed! I somewhat over-use this in Rust to initialize an immutable variable with mutating code.

  let var: Vec<u32>;              // this one is immutable, will be initialized later
  {
    let mut var_;                 // mutable
    …                             // initialize var_ with some mutating code
    var = var_;                   // now move var_ to var, initializing the latter
  }


This is a bit simpler as:

  let var = {
      let mut var = ...

      var
   };
that is, you can assign the result of the block directly. That way you don't need two variables with the _ name as the second.


Couldn't you just write:

  let var: Vec<u32> = {
    let mut var_;
    …
    var_
  };
Or, better still:

  let mut var: Vec<u32>;
  …
  let var = var;


You can also initialize it to an expression, e.g.

    let var = {
      let mut var_ = Vec::new();
      var_.push(1u32);
      var_
    };




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

Search: