3 ms·
I find myself increasingly doing this in Rust: let lines = { let ret = vec![]; // Open file // Read into ret ret };
by sinhpham 9y ago
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.
- sbov 9y agoIn 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 }
- maxxxxx 9y agoI do this a lot in unit tests where a pattern is repeated.
- fishywang 9y agoIn 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 }