11 ms·
Why Rust closures are somewhat hard
- amelius 8y agoI really want to like Rust. But writing a doubly linked list was already shown to be difficult [1], and now closures are too ... It really feels like this is not a language to "get things done". Please let someone prove me wrong. [1] https://rcoh.me/posts/rust-linked-list-basically-impossible/ https://rcoh.me/posts/rust-linked-list-basically-impossible/
- mjewkes 8y agoA doubly linked list is not a good candidate to be written in _safe_ rust. Lots of other problems are.
- 1qaz2wsx 8y ago+1. As a C++ developer with decade of experience, I'm finding Rust hard. It is a truly innovative language with a rising ecosystem that makes life of developers easier in a lot of areas. But overall the safety and performance benefits do not seem to be worth the effort if you just want to get things done. My thinking is, if you are smart enough to master Rust, and you do need tight control of memory that GC overhead is not worth it, you are probably smart enough to write safer C++.
- nicoburns 8y ago> My thinking is, if you are smart enough to master Rust, and you do need tight control of memory that GC overhead is not worth it, you are probably smart enough to write safer C++. Easy for you to say as a C++ developer! As someone who came to Rust as a JavaScript/PHP/Python developer, I greatly appreciate Rust checking all my work. I'm plenty smart enough to work out the problems that the compiler picks up (once I have an error message I can google for explanations and solutions), I just don't/didn't have the experience to know that my naive code was going to cause problems.
- int_19h 8y agoMost of the issues described in the article on closures are identical to C++, or have direct C++ equivalents (it even helpfully points them out!).
- glandium 8y ago> if you are smart enough to master Rust, and you do need tight control of memory that GC overhead is not worth it, you are probably smart enough to write safer C++. As both a C/C++ developer with more than a decade of experience, and a Rust developer, I'll posit that if you are smart enough to master Rust, you still aren't smart enough to write safer C++. Not even close. Rust might enlighten you in some ways, and avoid you doing some mistakes in C++, but without e.g. a borrow-checker, there are still too many ways to shoot yourself in the foot in C++, that Rust would find at compile time, while the equivalent C++ code would fail at runtime. If you're lucky and happen to hit the error conditions when you test it.
- ramenmeal 8y agoHas there been any responses to this by some rust guru's? I don't follow rust too closely but am curious about the ownership model
- steveklabnik 8y agoYes, there's been lots of writing about this. I've been implementing linked lists in various ways over the last week (including right now), so this is very top of mind for me. The core of it is two things: mindset, and how programmers think about learning languages. Mindset: there's two things at play here. The first is that C programmers tend to reach for linked lists by default. It's a CS 101 data structure. Not super hard. A Rust programmer, however, would reach for a vector (or a deque) by default. For many use-cases, these structures are better, thanks to amortized allocations + cache reasons. As always, depends on exactly what you're doing. The second mindset issue is write vs use; C programmers tend to write their data structures themselves. Rust programmers tend to use packages. If you've determined that you need a linked list in Rust, you don't start writing one: you "use std::collections::LinkedList;". It's a doubly-linked one, so maybe that's not what you need. In that case, you go on crates.io and see if someone has already written what you need. (225 hits incidentally: https://crates.io/search?q=linked%20list https://crates.io/search?q=linked%20list) Only if that fails do you write it yourself. As the ecosystem has filled out, this happens increasingly infrequently. So "a linked list is painful to write" just doesn't apply to the vast, vast majority of Rust programmers who are simply getting work done. Learning: because linked lists are a CS 101 data structure, they're something people reach for when learning Rust. But different languages are different, and Rust is not C. Writing a good data structure isn't a beginner Rust topic, it's an intermediate to expert one. There's stuff Rust makes easy that C makes hard as well. You can't assume that topics are equally difficult across the languages. Even then, there's http://cglab.ca/~abeinges/blah/too-many-lists/book/ http://cglab.ca/~abeinges/blah/too-many-lists/book/. TL;DR: linked lists being painful to implement is sorta true, but also not really relevant, other than people who try to learn Rust by building them and having a bad time. (Which is unfortunate, but many people don't as well, or have at least heard that they're hard and so have the right expectations going in.) Now, I've gotta get back to my benchmarks: std::collections::LinkedList is twice as fast as my straightforward C linked list, and I gotta figure out where I messed up. I'll check back later for replies. (If you're interested in this benchmark I'm working on, https://godbolt.org/z/lF1D85 https://godbolt.org/z/lF1D85 is the disassembly. They look so close, I have no idea why 100,000 pushes, the Rust impl is taking 7.9038 ms on average, whereas the C impl is taking 15.413 ms. That seems very wrong...)
- k__ 8y agoWhy do you write your own basic data structure?
- wahern 8y agoThere's a theory of programming that says software development is fundamentally a process of devising and implementing data structures specifically tailored to the problem at hand. This theory says well written software doesn't (and can't) simply stitch together various data structure implementations through generic interfaces. That in robust, elegant software there's no dividing line between where the fundamental data structure is implemented and where the application specific logic resides. One classic example is the Thompson NFA. The argument is that the path to devising elegant solutions like the Thompson NFA is to think in terms of simple data structures tailored to particular problems. A toolbox of pre-implemented data structures is of little value because implementation matters and often needs to be tailored to the problem. It's not a matter of performance; it's that if your data structure implementations aren't tailored to the problem your use of them will require overly complex, opaquely layered code and you would (justifiably) architect your solution some other way; a way better suited to gluing together libraries but poorly suited to the actual functional problem. I don't think this particular theory is right in any absolute sense. But I think it's more right in the domain that Rust targets, which means I believe the cost of implementing things like linked-lists and trees is underestimated; and that how often people will end up resorting to unsafe code (or recapitulating reliance on unchecked memory access, such reinventing pointers as indexes into arrays) is underestimated.
- k__ 8y agoInteresting assumption! Most of my theoretical computer science knowledge was based on the fact that there are a bunch of basic well known algorithms and data structures and you build everything out of this. Do you have resources on the approach "invent" such things on your own so they are better suited for the problem?
- dman 8y agoI have had to write specialized lookup tables multiple times for the problem at hand. In every case doing something custom gave non trivial speedups over existing off the shelf solutions.
- phyzome 8y agoIt looks like they're different kinds of difficult. From your link: « In hindsight and with a deeper understanding, it’s not surprising why a doubly linked list is so problematic. Each variable can only have 1 owner. If prev and next both hold pointers to a middle node, which is the owner? They can’t both be the owner. If one is the owner, another can borrow. But Rust won’t let you mutate while someone else is borrowing, so neither could actually modify the list! In general, if you have loops in your object graph you’re out of luck. » So the solution for doubly linked lists is to write some "unsafe"-marked Rust once, really bang on it, and ship that in a crate full of generic data structures. This is acceptable to me; it's no worse than C. With closures, it sounds like the issue is not that it's impossible, but that the lifetime and mutability analysis get tricky in some cases.
- wahern 8y agoWhat's interesting is that the Rust community has turned this difficulty on its head: linked-lists are unnecessary, performance killers, and generally evil. (Ditto for trees.) That's all true, if you squint really hard, gloss over the equivalencies, discount the additional complexity, and ignore the basic simplifying elegance of linked-lists (particularly the so-called intrusive data structure implementations). But it's dramatically overstated because of a certain defensiveness. What is absolutely true is that cyclical referencing is the bane of static analysis, and anathema to a language that leans so heavily on its typing system for modeling language semantics. What you think that implies depends on your faith in how far type-based, lifetime-based static analysis can go toward addressing larger issues in the software ecosystem.
- detaro 8y agoYou hear fairly similar statements about linked lists from the C++ crowd too, where they're trivial to implement, so it's unlikely it's just defensive excuses.
- deleted 8y ago[deleted]
- whyever 8y agoThey are are arguably about as trivial to implement in Rust. It becomes tricky when you add constraints: usually you want to avoid unsafe code, but even then you can just implement them on top of a vector and bypass any lifetime/aliasing issues.
- deleted 8y ago[deleted]
- jcelerier 8y ago> linked-lists are unnecessary, performance killers, and generally evil. that's true on any CPU with more than 16kb of cache. linked lists were a good idea at the time of 486, not so much at the time of modern CPUs with 8+ megabytes of L3. See https://baptiste-wicht.com/posts/2012/12/cpp-benchmark-vector-list-deque.html https://baptiste-wicht.com/posts/2012/12/cpp-benchmark-vecto...
- stormbrew 8y agoClosures are a fair thing to want to be easy, but I'm not sure "can't write basic data structures that someone has already written better than you will" isn't a feature. Truth is that one of the reasons they're "hard" in rust is because it's actually harder than people think to make a proveably correct linked list (in the absence of a cycle-safe garbage collector). It's really just surfacing a cognitive dissonance common to the programming world. (Note for clarity: closures are also hard to prove correct in the same environment, but there's a lot more need to write them in normal working code)
- electrograv 8y agoAdditionally: Due to this, Rust will encourage you to gravitate towards pattern like immutable collections, or other 'functional-esque' coding styles. As a result, you usually end up writing code that's far more inherently reliable at runtime than something like a mutable doubly linked list. Just learning to code in 'idiomatic Rust' has made me a better coder overall, IMO, as has learning to write in pure functional languages. I think most people definitely underestimate the amount of caution / design care required to implement even something as simple as a linked list with zero bugs, memory leaks, potential infinite loops in member functions, etc. The Rust compiler prevents entire classes of bugs at compile time, and just requires that you to write an 'unsafe' block if you really want to go ahead with this sort of code without the compiler complaining. This emphasizes that you really do have to be careful and think through the logic and memory ownership semantics of the code you just wrote. People used to GC'ed languages will find this annoying to have to worry about at all, but that is inherently the price you must pay to eliminate GC pauses/overhead. I'm not saying you should never use data structures that Rust makes hard to write, but that going into Rust thinking it's just going to be 're-skinned C++', or 'as easy as a GC language' is going to be a recipe for disappointment. If you allow yourself to learn a new way of thinking about low/systems-level coding, you may be pleasantly surprised. But if you're too "set in your ways" (whether it be of C/C++ or JS/Python/etc.), you're not going to see Rust's benefits. Rust is a deeply different language than C/C++. I think people forget this, primarily because Rust is so powerful and efficient (with no inherent language overhead, allowing it to be used even in embedded environments and other systems programming tasks).
- pitaj 8y agoWriting a doubly linked list isn't that hard [1], and if you're willing to do it in unsafe rust, it's not any harder than any other language without a GC. [1]: https://www.reddit.com/r/programming/comments/7zbi6s/why_writing_a_doubly_linked_list_in_safe_rust_is/dunjytf/?context=0 https://www.reddit.com/r/programming/comments/7zbi6s/why_wri...
- dman 8y agoI think unsafe was poorly named since the name discourages its use.
- orf 8y agoI think the point was to discourage it.
- oconnor663 8y agoI think the name has done an excellent job of discouraging its use. Everyone in the community seems to agree that "contains unsafe code" is a big deal for a crate, and that taking that on when it isn't obviously necessary is sloppy.
- withoutboats 8y agoThis is the sort of really impressively shallow and baseless analysis that makes Hacker News so enjoyable to read. These two blog posts have really nothing to do with one another, are describing unrelated problems with unrelated things, sharing only the fact that they both have to do with the Rust language and both describe something as difficult (but meaning pretty different things by the word) and you draw a conclusion that "Rust is not a language to 'get things done.'" I don't know how to prove that Rust is "a language to 'get things done'" - this seems like an almost meaningless qualifier - but many people (including me) are getting things done using Rust every day.
- electrograv 8y agoI actually find that Rust is far more productive overall, when accounting for debugging time (or lack thereof) vs other languages! It is precisely because Rust makes it difficult to implement a lot of bad ideas, that I find myself spending a tiny fraction of my time debugging Rust applications vs C/C++/others (including even high level GC languages). I love that Rust encourages inherently reliable code, while also not stopping you from writing "unsafe" blocks in the (rare) cases where they're necessary. In fact, in every case so far where I thought 'maybe I should try an unsafe block', I started to realize that implementing this idea or data structure was actually riddled with hard memory management problems, or race conditions, etc. that Rust was preventing from even being possible at all. P.S. Of course there's a steep learning curve to Rust at first, but it's not fair to count that against Rust -- unless you also weigh against C++ all the years it takes to really master it. IMO, Rust's learning curve is far less steep and painful than C++, it's just that many of us are biased and comfortable having already climbed the C++ learning cliff (so we tend to forget it is there, and how bad it is).
- antaviana 8y agoI did a basic test Rust program: load to strings certain files in a zip file. The first file in the archive happened to be UTF-16 instead of UFT-8 so a vanilla read_to_string for the file in the archive did not do the trick. I googled a bit and it seemed that, in order to be efficient, had to be done with unsafe code. Maybe I was very unlucky, but I was surprised that 5 minutes after trying rust for the very first time I had to use unsafe code.
- shawn 8y agoIt is decidedly not a language to get things done. I say this as someone who put himself in the unfortunate position of challenging BurntSushi (author of ripgrep) to a coding duel, bragging that I could get LuaJIT to match his XSV performance (https://github.com/BurntSushi/xsv https://github.com/BurntSushi/xsv) It took hours to figure out how to implement this in rust: https://github.com/sctb/lumen/blob/master/bin/lumen https://github.com/sctb/lumen/blob/master/bin/lumen If you want to see an "expert" programmer's attempt at making sense of the language, here you go: https://gist.github.com/shawwn/4d7a89188cac72f3e591f47c84d3ca49 https://gist.github.com/shawwn/4d7a89188cac72f3e591f47c84d3c... Now that it's done though, I see why people fall in love with Rust. It's really satisfying seeing Lumen's startup time drop from 200ms to 100ms. But yes, like -- dude, at one point I just wanted to write a for loop like this, to grab some environment vars: let mut lumen_host = "luajit"; let mut lua_path = ""; let mut node_path = ""; for (name, value) in env::vars() { if name == "LUMEN_HOST" { lumen_host = &value; } else if name == "LUA_PATH" { lua_path = &value; } else if name == "NODE_PATH" { node_path = &value; } } println!("{} {} {} {}", bin, lumen_host, lua_path, node_path); Good luck with that! I'm sure there's a way to coax Rust into please-allow-me-to-just-compile-this, but the borrow checker is a cruel taskmaster. Whatever the syntax is, that's not it, and spending literally an hour trying to figure out how to store an environment variable into a separate variable doesn't feel very productive. That said, Cargo is amazing. It's truly a wonderful, delightful piece of software. Cargo crates plus a dynamic language seems like a recipe for success.
- withoutboats 8y agoThe difference between &str and String is one of my least favorite parts of Rust, but I made your code compile with some pretty trivial changes: https://play.rust-lang.org/?gist=66789a8e86e3c2fd1803adc4bec89957&version=stable&mode=debug&edition=2015 https://play.rust-lang.org/?gist=66789a8e86e3c2fd1803adc4bec...
- steveklabnik 8y agoIs there a reason you looped through env::vars() rather than calling env::var on each key you wanted? That'd be much more straightforward: let lumen_host = env::var("LUMEN_HOST").unwrap_or(String::from("luajit")); let lua_path = env::var("LUA_PATH").unwrap_or(String::new()); let node_path = env::var("NODE_PATH").unwrap_or(String::new());
- coldtea 8y ago>But writing a doubly linked list was already shown to be difficult [1], and now closures are too ... That's a very shallow concern. Writing a "doubly linked list" is what you do in Rust with unsafe or will several other ways. It's also not something you usually do, you just use one of the several implementations in the library and third party libraries and get on with your actual program. And this doesn't show closures to be that hard at all. It's the basic dynamic vs statically typed language thing, plus a couple of caveats to keep in mind. Hardly anything to write home about. The fact the tons of people use Rust for production code already, and love it, doesn't give these concerns pause?
- rwmj 8y agoSurely the problems behind a doubly linked list apply to similar data structures (trees and graphs, notably - of which there are many more varieties than could be covered by a standard library). Writing a tree without resorting to unsafe seems like something which would be important.
- amelius 8y agoYes, for example a DOM tree where every node has a backlink to its parent.
- TheCoelacanth 8y agoConsidering that one of the largest and most prominent Rust projects (Servo) is a browser, that is obviously not an insurmountable problem.
- pjmlp 8y agoServo has a GC implementation for handling DOM nodes. https://github.com/servo/servo/blob/master/components/script/docs/JS-Servos-only-GC.md https://github.com/servo/servo/blob/master/components/script... https://manishearth.github.io/blog/2015/09/01/designing-a-gc-in-rust/ https://manishearth.github.io/blog/2015/09/01/designing-a-gc...
- oleganza 8y agoA team of three people including me have used Rust _daily_ for almost a year now for at Chain[1]. Rust is _by far_ much easier to use than C or C++ and lets us get things done with clear design, record-breaking performance[2] and utmost safety[3]. Basically, people who avoided C/C++ for years as unsafe, lacking usable abstractions and generally hard to use, switch to Rust and enjoy it. [1] Bulletproofs crypto library: https://github.com/dalek-cryptography/bulletproofs/ https://github.com/dalek-cryptography/bulletproofs/ [2] https://blog.chain.com/faster-bulletproofs-with-ristretto-avx2-29450b4490cd https://blog.chain.com/faster-bulletproofs-with-ristretto-av... [3] https://blog.chain.com/bulletproof-multi-party-computation-in-rust-with-session-types-b3da6e928d5d https://blog.chain.com/bulletproof-multi-party-computation-i...
- fpoling 8y agoIt is trivial to implement doubly linked list. Just use unsafe. What is difficult is to implement it in the safe Rust. But then try to proof that, say, C++, code doing the same is safe. It is very hard. Besides, if one really wants cyclic structures in safe Rust, one can always do ancient Fortran trick and just represent pointers with array indexes. It may even be faster due to more cache-friendly memory layout.
- drbawb 8y agoPlease consider listening to Bryan Cantrill's thoughts[1] on using Rust to, as you say, "get things done." -- In the presentation he explicitly calls out how learning Rust by trying to bang out a "trivial" data structure is very much the wrong approach. He posits that to understand the value(s) of Rust you must be willing to approach it from first principles. Let that sink in: a kernel & distributed systems programmer w/ decades of experience had to resist the urge to just bang out a linked list & instead opt to learn the language from first principles. That being said he seems to be quite[2] happy[3] with the language. [1]: https://www.youtube.com/watch?v=aWbGPMxs0AM https://www.youtube.com/watch?v=aWbGPMxs0AM [2]:https://twitter.com/bcantrill/status/1035335403186806784 https://twitter.com/bcantrill/status/1035335403186806784 [3]: https://twitter.com/bcantrill/status/1038495464692146176 https://twitter.com/bcantrill/status/1038495464692146176
- glandium 8y agoAnd for kicks, here's a quote from that Youtube video you link: "So that was a surprise. (...) I've done zero profiling on this. I've made absolutely zero attempt to make this thing faster. None. In fact, you can pretty reasonably argue that I've gone out of my way to make it slower. And we are 40% faster than my C." Which doesn't mean that rust is faster than C, but that changing your approach can, in fact, lead to results you wouldn't have expected.
- oconnor663 8y agoQuote starting at about 1:05:00. Pretty nice :)
- _hardwaregeek 8y agoI always find it funny when people propose adding closures to C. Because the moment you add closures (in the way most languages implement them, not Rust's implementation), you're adding automatic boxing, which implies garbage collection and a runtime. Which basically means you've added objects. Which...sure you could do, but at that point, you're not adding to C, you're just making a new language.
- saghm 8y agoWould it be possible to add C++'s implementation to C, or does it rely on other C++ features that C doesn't already support?
- whyever 8y agoC does not have `auto`, so you couldn't store closures in local variables.
- v_lisivka 8y agoIn C, you can use typeof(). #define max(a,b) \ ({ typeof (a) _a = (a); \ typeof (b) _b = (b); \ _a > _b ? _a : _b; }) https://gcc.gnu.org/onlinedocs/gcc/Typeof.html https://gcc.gnu.org/onlinedocs/gcc/Typeof.html
- wahern 8y agotypeof is supported by everything[1] except the C standard. It was rejected in the 1990s and nobody on the committee seems to want to revisit the decision. To be fair, typeof is not as useful without statement expressions (`({ ... })`), and statement expressions aren't as widely supported. [1] All the major compilers support it (clang, GCC, IBM, Intel, Microsoft, Solaris, etc), plus or minus underscores in the identifier.
- Longhanks 8y agoYou’re not wrong, but C has __auto_type (at least GCC and clang support it, no idea about MSVC): https://gcc.gnu.org/onlinedocs/gcc/Typeof.html https://gcc.gnu.org/onlinedocs/gcc/Typeof.html
- madeuptempacct 8y agoThis may be way too much for this topic, but where do closures get stored?
- sam0x17 8y agoIf they are "boxed" they are on the heap, otherwise they are on the stack.
- int_19h 8y agoDon't they do small object optimization? In C++, implementations of std::function usually do that to avoid allocating for most common cases.
- steveklabnik 8y agoClosures don't implicitly box, so any boxing would be done by the user directly, and so that would be up to them.
- int_19h 8y agoI meant the Box type itself. In C++, std::string and std::function are usually intentionally padded, so that when the data is small enough, it can fit inside the object itself, rather than storing the pointer to heap-allocated storage.
- steveklabnik 8y agoA Box'd Fn is two pointers: one to the code, and one to the data. The only way that this would work is if the data was a single usize, which is not likely to be many useful closures. In theory it could happen, I guess...
- int_19h 8y agoThe idea is that you intentionally pad your type with fields that don't do anything other than provide a scratchpad for extra storage, much like over-allocating an array to avoid resizing on append. If the stored data is smaller, those go unused, so if you pick the wrong amount, the overhead is too great. But if you hit the sweet spot, it has very significant perf benefits, not only because it avoids hitting the allocator on copies, but also because of data locality. BTW, why wouldn't a lambda with a single usize field be common? I thought Rust captures everything by borrow by default; if so, doesn't the implementation simply store a frame pointer inside the lambda, and use it to access the captured variables? It seems like an obvious optimization...
- Animats 8y agoRust decides at compile time how long the data stored in a closure must live. You can create situations where that's hard to define, and the compiler, properly, won't permit that. It's very clever. (Rust tends to use closures heavily, in places other languages don't. So they need all the performance they can get.)
- glittery 8y agoOne thing that's always concerned me about Rust is that everyone mononorphizes everything (e.g. closures are always unboxed except in the rare cases where dynamic dispatch is necessary). Hopefully this is a baseless fear, but isn't this a recipe for executable bloat?
- chc4 8y agoYes, and there have been some cases of people hitting very large binaries and having to put effort into slimming them down. In most of those cases it's due to either wanting to run in very constrained space or distribution size, and then the problem is due to some blanket impl for a bunch of types that can safely be removed though. There are a few cargo submodules that will do executable size analysis with regard to monomorphization to show the outliers. There's not really a good solution for this. Having your code be fast by default in exchange for more space seems like the trivially correct choice to make when most people have hundreds of gigabytes of free hard drive space and binaries don't get above a few megas, while CPU speed has stagnated. If they want runtime type matching instead, they can still do it.
- jandrese 8y agoVery large binaries can be a performance problem too if their access patterns end up trashing the cache. Memory access is a common bottleneck on modern CPUs. It depends how big "big" is in this case, and how much of it actually gets executed repeatedly.
- withoutboats 8y agoIt can be! And arguably people have leaned too hard on the decisions made in the std as an example: in std, everything is generic so that it can be inlined well, because std APIs underlie everything. At the application layer, this is not obviously what you want. However, in many cases, a well designed generic API will be able take a trait object in the place of `T`. That way, at the application layer, you can decide to pass trait objects around, reducing code size and - maybe more importantly to you - compile times. cargo does this for example in some places where the performance regression is insignificant but it saves noticeable compile time. Sometimes libraries accidentally don't set things up so that you can pass either a concrete `T` or a dynamically dispatched trait object to their APIs; we're hoping to find a way of making it less likely for this to go wrong in the future.
- sevensor 8y agoSo, if you're writing in Rust, why not box everything, most of the time? Pay the cost of dereferencing to make it easier to reason about closures? Save unboxed values for situations where they're either trivial to reason about or you're sure there's a performance problem? Is this regarded as bad form? (I don't really know Rust, but I'm watching with interest. As my comment may suggest, I'm more familiar with C and Python.)
- glittery 8y agoUnboxed closures aren't any harder to reason about than boxed closures, and any function that accepts an unboxed closure accepts a boxed closure, too, which is why library authors should almost always prefer accepting unboxed closures (as withoutboats said in another comment.)
- steveklabnik 8y agoYou can. I'm not sure how much it's done or isn't done, really. Pre-1.0 Rust even had mandatory boxed closures, and until fairly recently (1.26?) you still had to box them in more situations than you do today.
- blt 8y agoI think the general philosophy of Rust is that programmers should think about the data ownership semantics of their programs. Rather than boxing everything to make it easier to reason about closures, one should strive to write programs that use closures in a way that is easy to reason about.
- int_19h 8y agoIf you intend to box everything most of the time, you might as well just use a higher-level language with GC, like C# or Swift.
- oleganza 8y agoBecause, contrary to what the OP is saying, writing normal Rust is actually easy and straightforward. So you don't have to "box everything" by default. You only need that when you do some asynchronous work via generic interfaces.
- 13415 8y agoEverything in Rust is somewhat hard.
- phyzome 8y agoThat's the tradeoff you get for compiler-checked memory management. It's hard to write safe code. C is easier because you don't have to prove it's safe.
- mmirate 8y ago... to get an initial implementation of. It's much easier to read, debug and refactor Rust code than in almost any other language that offers similar resource-efficiency.
- 13415 8y agoAda is way easier to read, debug, maintain, and refactor than Rust. So is the majority of other halfway safe languages (except Haskell, maybe).
- mmirate 8y agoHalfway-safe languages (including Haskell) that aren't Rust, have a nasty habit of eating memory (and usually CPU time, too) for breakfast, compared to equivalent programs in C, C++ and Rust. That's what I meant by "resource efficiency".
- coldtea 8y agoCompared to what? C++? C? Python?
- skybrian 8y agoIf you're interested in writing code for maximum readability, might it be simpler to write for loops more often, rather than tricky type signatures?
- steveklabnik 8y agoThis is up to taste; I find map/filter/collect/etc to be cleaner than a for loop 95% if the time. For that 5%, there’s still for loops.
- ealhad 8y agoThe problem of a for loop is actually that it's just a for loop. When you see filter, map, or max_by, you know what the code does right away.
- cipherzero 8y agoAs someone who has recently started learning rust i can safely say closure issues where the hardest and most confusing things to learn how to fight with the borrow checker. This is especially the case since futures are becoming popular and require closures to be useful (obviously.) This post covers a lot of the things I had to recently learn the "hard" way. Thanks!