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

I find myself increasingly doing this in Rust:

    let lines = {
        let ret = vec![];
        // Open file
        // Read into ret
        ret
    };
    let processed_data = {
        // Open another file
        // Use lines
        // Construct ret
        ret
    };
    ....

You get the best of both worlds this way: scoped, meaningful names like with sub-functions and the continuity of a long one.

Everything is an expression is an underrated feature of Rust.




In at least Java, and probably more languages, you can also use braces to limit variable scope. E.g.:

  List<String> lines;
  {
    int whatever;
    lines = new ArrayList<>();
    // modify lines
  }

  List<Object> processed_data;
  {
    int whatever;
    processed_data = new ArrayList<>();
    // modify processed_data, using lines
  }


In Go something similar to this is actually more common because of `defer`, e.g.:

    if err := func() error {
      f, err := os.Open(filename)
      if err != nil {
        return err
      }
      defer f.Close()
      // work with f
      return nil
    }(); err != nil {
      return err
    }


I do this a lot in unit tests where a pattern is repeated.




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

Search: