7 ms·
I 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 n
by amelius 8y ago
I 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 :)