4 ms·
Interesting to see this as a novel thing in another ecosystem. Rust actually uses "stream" manipulation as a default way of dealing with things that might other
by doomrobo 11y ago
Interesting to see this as a novel thing in another ecosystem. Rust actually uses "stream" manipulation as a default way of dealing with things that might otherwise be expressed as full data structures. For example, the equivalent to one of the code snippets in the article would be:
BufReader::new(File::open("myfile.txt").unwrap())
.lines()
.enumerate()
.map(|(i, line)| format!("{}: {}", i, line.unwrap()))
.take(1)
.next().unwrap()
(formatted for non-monospace font readability). Note the .unwrap() is where error handling should normally happen.
- meowface 11y agoThe problem with "stream/generator as default" is the boilerplate you constantly have to add. In Python 3, for example, map() returns a generator. So you can no longer transform a list into another list with `new = map(func, lst)`. You have to do `new = list(map(func, lst))`. One of the most subtle gotchas when upgrading from 2 to 3 is having to wrap list() around functions and methods like map(), range(), dict.items(), etc. Discussion I've seen about Rust on less moderated websites often seems to make fun of the .unwrap() spam seen in a lot of programs, to the point of the mockery even dominating some discussions. Streams and lazy evaluation are really nice, but sometimes you just want some nice procedural handling.
- Jweb_Guru 11y agoWhen using Rust for more than toy programs (which, assuming I am thinking of the same "less moderated" websites that you are, is unlikely to be the experience of the commenters), unwrap() isn't particularly common outside of main(). You generally want to handle the error cases. It's used a lot in examples because they have to function as one-offs.
- icebraining 11y agoAll the boilerplate you need to add is lmap = lambda f, l: list(map(f, l)) somewhere in your project, then use new = lmap(func, lst)
- Willyfrog 11y agoOne has to wonder why this is not included in the functools or some other module.
- icebraining 11y agoDunno, to promote generators? I'd say people often convert to list for no good reason, so adding friction might discourage that. Then again, map() and friends are not exactly the recommended way, list comprehensions and generator expressions are usually preferred by the BDFL.
- doomrobo 11y agoAs another comment mentioned, .unwrap() is really useful for testing things out, but any legitimate (read: with intent to be used for some practical purpose) library or program is going to handle most errors. One edge case may be calling unwrap() in a thread that should die if the unwrapped operation doesn't succeed.