332 points · by muizelaar · 10y ago · 197 comments
Another thing that is still tricky for me is figuring out when I should use 'unsafe' blocks in my code. Is it to be avoided if at all possible, or should I go there any time the 'safe' part of the language is making it difficult to express what I want? The meme that Rust is C++ without SegFaults and or race conditions is a bit misleading since the actual guarantee is that you don't get SegFaults or Race conditions outside of Unsafe blocks, and any nontrivial project will make use of unsafe blocks.
They're tagged unions with no implicit heap allocations. I guess we should at least document that in the reference (though we don't want to overspecify, because we do some tricks in the compiler to try to avoid leaving space for the tag if we can). But I don't think it'd be a good idea to document this straight away in the book: the goal is to make Rust easy to pick up, and adding more information than necessary when introducing enums (which a lot of folks will only see for the first time in Rust) isn't going to do people any favors.
> What about iterators?
The documentation for Iter explains this pretty well, I think: https://doc.rust-lang.org/stable/std/iter/
It even shows the exact implementation of (basically) Range, to give you an idea.
That said, it would probably be worth calling out that most iterators are guaranteed not to allocate. Note, though, that that isn't a hard-and-fast constraint that implementors of the trait have to abide by—you can make your own iterators and implement them however efficiently or inefficiently you like.
> The meme that Rust is C++ without SegFaults and or race conditions is a bit misleading since the actual guarantee is that you don't get SegFaults or Race conditions outside of Unsafe blocks, and any nontrivial project will make use of unsafe blocks.
They'll make use of unsafe blocks transitively, by using unsafe code in the standard library or well-tested crates. Think of these unsafe blocks as part of the compiler: you trust the compiler to generate correct machine code when you type "a + b", so likewise you trust the standard library to do the right thing when you say "HashMap::new()".
It is not the case that most projects should use unsafe themselves everywhere: that usually just makes life harder. The primary exception is if you're binding to C code, in which unsafe is unavoidable.
I haven't had to resort to "unsafe" blocks in the Rust I have written so far but "ffi" is one use case for unsafe blocks. Another resource that I have yet to read is "https://doc.rust-lang.org/nomicon/" which seems to explain how to write unsafe Rust code.
Re: unsafe, I think that's tough. My personal feeling is that many of Rust's selling points rely on minimizing the use of unsafe (i.e. limiting segfault-relevant portions of the code), and that there are frequently ways to make things work and also make them fast without using unsafe. What's an example where you found yourself thinking about using unsafe instead of a more complex safe construct?
(Somewhat related to this, and especially for anyone reading who might try Rust, I cannot recommend getting on IRC strongly enough. The Rust IRC channels are by and large incredibly friendly and helpful, and for better or worse that's where a lot of the knowledge in the community is currently collected, not as much SO or blogs)
Definitely. It was taught in school and there's pretty good guides for it online (maybe not caught up to c++11 and beyond, but the fundamentals are there). You're right that it is not readily available for most languages, but when you need to get serious about performance you either are going to have a guide or spend a lot of time looking at assembly/bytecode. To be fair, I'd probably still have to inspect generated code sometimes, but it's nice to have good instincts for how things run to guide your design/implementation so you can spend less time looking at assembly.
When doing very performance sensitive things in Rust, I usually find myself asking questions a lot on IRC and looking at disassembly in perf.
To answer some specific examples you cited above: I'm pretty sure that enums are (almost?) always equivalent to tagged unions. If you have an enum which doesn't contain any data, then I believe it's representation is just the tag. Iterators are just structs with methods, the various generic functions they implement are monomorphized and then optimized by LLVM.
Sure! But that's okay. Just don't use 'quantity of unsafe blocks' as a metric of quality and you'll be all set. Think of it like so: don't use it until you have to and try not to have to. For me, that means consulting experts on IRC (etc), "How can I express this goal in idiomatic rust?" No different from learning C/C++ for the first time, IMO. And if no good way exists you may have to use unsafe blocks.
Unsafe blocks aren't bad, just like #pragma-disable-this-warning and --static-checker-I-did-it-this-way-by-design aren't bad. They mean that you've thought critically about the pros and cons and you are going into this decision well aware of the risk. On the flip side they should be the first blocks to closely examine in the face of failures like segfaults/races/etc.
I don't think that's actually true? Most projects make use of no unsafe outside of stdlib and a handful of crates.io crates.
edit: This is not counting FFI though.
(ie sure, maybe you're not writing unsafe yourself, but you'll quite possibly hit an issue where you have to dig into a crate that does)
And even if you do use unsafe, you can still use it to build 'safe' abstractions on top of. the idea is that your unsafe code is quarantined and abstracted, and you build on top of it. std::collections is a great example of this.
I'll certainly be reading your link below, thanks for that!
It soulds like an informal "specification" of #[repr(c)] or #[repr(packed)] for common platforms would also be useful for FFI.
This. The primary reason to choose rust is performance -- that is, you want more advanced abstraction/safety capabilities than C++, and you want that with the same or better performance. And performance implies CPU cost and memory usage/layout control. There really isn't any point otherwise.
Therefore, going into at least a little bit of detail on the idioms and performance impact of those idioms is important. Rust is a supposed to be a systems programming language to replace C, do not pretend it's as abstract as ML in the documentation.
What throws me for a loop when learning Rust isn't high level details like the borrow checker or sum types, it's what is happening with cpu & memory[1]. When things are copied, when they aren't, how much do the std derives cost, matching cost, sum type storage cost, etc. Because while the semantics are similar to C++, they are not the same. And you don't have to go nuts specifying it (compilers will differ), but at least give a general understanding/hint of what to do and what to avoid.
To be fair, the doc does have this scattered about, but it doesn't feel a priority (There are many things I've had to search the web for or ask on #rust, or just look at disassembly for).
[1] To take an extremely simple example, RVA is something Rust supposedly does much more consistently than C++, thus returning a new struct by value to be placed wherever is idiomatic. However this isn't called out very clearly (the last time I checked) in the doc, and to a C programmer, it feels very wrong. Stuff like this is extremely important, otherwise we'd just ignore performance and use a JVM based language with the same (or better) abstraction features and a faster compiler. :-)
The main reasons to use unsafe code are when you're doing FFI and have to regrettably talk to C/++ libraries, or when designing new abstractions with a safe API boundary. It's tricky to ensure that the former is safe since you eventually have to trust C++ (but then, that's not Rust's fault). It's not hard to ensure that the latter is safe. Looking at a page of code and ensuring that it can't cause segfaults is a much easier task than doing it for the entire codebase.
This is almost all the unsafe code out there. There's a bit of it used for doing manual optimizations. When Rust doesn't let you do what you want, often there are abstractions like RefCell that have a small cost that you can use (and they contribute to the overall safety). In case this happens in performance critical code, you can use unsafe again, but this is very rare.
In Servo, for example, almost all of the unsafe code is of the first two kinds. I've been hacking on Servo for years and didn't write much unsafe code at all -- when I did, it had to do with talking to Spidermonkey, and even that was pretty rare. More recently I'm working on integrating Servo's style system into Firefox (which is C++), and only now have I been regularly writing unsafe code. Even for this project the unsafe code I'm writing abstracts away the inherent unsafety of Firefox's C++ so that others can talk to Firefox with safe Rust code.
But many projects have no unsafe code at all. It's not that common to have unsafe code.
> it was difficult for me to find performance characteristics of the underlying abstractions and std library (for example, are algebraic data structures just tagged unions or does the compiler do more fancy things with them? What about iterators?).
Note that a C++ book won't help here for C++ too. What is a switch compiled down to? Does it use a jump table? :)
But yeah, it would be nice to have a thing for this. I don't think it belongs in the official book, but it should exist :)
ADTs are tagged unions. When non-nullable pointers are involved sometimes the tag is stored as a null pointer (e.g. `Option<Box<Foo>>` is a single pointer, and is None when null. Aside from that, nothing fancy.
Iterators compile down to the equivalent for loops. I can't think of any stdlib iterator which implicitly allocates; they all operate on the stack. In general these are just zero-cost abstractions, they will compile down the the code you would have written with manual loops. This is a recurring theme with the stdlib and even crates from the ecosystem. "extra" costs for abstractions are eschewed in Rust and will often be documented when they exist. So as a rule of thumb assuming that a random abstraction doesn't have an overhead unless explicitly mentioned is good.
When learning a new platform, it's always frustrating having to hunt for good code. I actually find these similarly important as docs (maybe even more because I tend to reference good open source for much longer than docs).
For example one for creating a microservice complete with routes, test cases, JSON support etc. Another for a command line application.
In languages with a steeper learning curve like Rust there needs to be more of an opinionated approach to teaching users.
The libraries having excellent documentation and pointing to apps that are similarly implemented tends to be better maintained, IMO.
cargo template-gen name somethingThis works particularly well for Java as the Eclipse compiler iteratively compiles and most IDEs will let you run a single method.
I imagine a similar stopgap could be used for Rust. I know its not the same but in some ways I have sort of disliked REPLs because its is very easy to accidentally delete or loose what you have type and you might as well make your playing around a test (just my 2 cents).
If you had something like that, I imagine you could probably write a Kernel for Jupyter which would be a huge win.
[1] https://github.com/PistonDevelopers/dyon
You might also be able to link the repl with Rust Language Server which could be linked with incremental compilation, letting you define modules or pub fn's dynamically.
The conversation can be followed/joined/whatever here: https://github.com/rust-lang/rfcs/pull/1774
I think it has a lot of great bonuses already. It's language ergonomics are that of a high-level language, yet it is extremely fast, and I can be very confident in my code if it compiles.
Rust is one of my favorite languages, keep up the great work guys.
If one thing more than any stands out it's Rust's commitment not just to building a language but building an incredible community. With how seriously the release processes are being taken to the way new people are welcomed. Serious kudos, I know it's not the most technically engaging work but it makes a huge difference.
Or are you saying that it is a pleasure to use, so you'll use it for smaller backends where development speed isn't that critical?
(Asking, not flaming. :-) )
I'll say it. At work, the backend is Rails, and I am a Rust contributor in my freetime. I am in the early stages of working on a framework for web apps in Rust & I believe it will be comparatively productive to Rails. Only your code will be faster and many bugs will be caught at compile time.
I think this is a great way to introduce large existing Ruby codebases to Rust in increments, much like Sentry demonstrated recently, but for Python: https://blog.sentry.io/2016/10/19/fixing-python-performance-...
(Given a modest test suite and checking parameters at external API interfaces, scripting languages didn't have much problems with bugs that could be found at compile time, imho.)
And the added bonus, is that my code runs 10-20x faster. So I really didn't give up anything to get the increased confidence.
However, I have to backtrack a bit here, because the largest Rust backend I've written was probably a little less than 10k lines. So while it was non-trivial it wasn't a massive undertaking.
If you're not spending significant time on rework it means your coworkers are doing it for you.
As version control has gotten better it's harder to hide who is to blame but most people still don't bother to look. Which means you get no feedback about how good your code is.
But sure, the world would be a better place if Rust, Go and/or Swift could fulfill that niche. I really don't know enough. (Go seems a bit boring. Rust is too new. Swift is a bit limited re Linux etc support.)
(I've seen the claim that some C++ gurus could develop features as quick as seasoned scripters, but... how many years did it take to get to that state? :-( )
(Sorry for coming back late.)
I like Rust and I'd like to use it more, but I generally lean on Go or C for writing anything that needs performance. I can't quite get past the awkward, fumbling stage with Rust. Go, on the other hand, was really easy to get acquainted with and not too substantial of an effort to get to strong expertise. I've been able to teach Go to junior devs with no background and hand off projects within a couple weeks. Rust is awesome, but fits in a very different bracket IMO.
Addressing the learning curve of Rust is important, but we aren't going to be able to do it by adopting concepts from Go or C. By and large, they just don't apply.
Ideally, all libraries (i.e. should be written by experts) are written in Rust, but applications are allowed to be written in RustScript.
RustScript would be optimized for lower learning curve. example[0]: - No `unsafe` allowed. - Everything is implicitly an `Arc<_>`. - All numerics are BigNum. - etc.
This is inspired by the popularity of using Rust within other languages, like Ruby. The way this would differ from using another language: All the Rust tooling would be the same. Realistically it would just be a different parser for the Rust AST. Therefore no memory layout issues, or FFI involved. Like syntax-sugar to the extreme, the compiler (except the parser) wouldn't even know the difference.
[0] I'm just listing simplifications, regardless of if they are a good idea.
But I'm not sure I agree that there would be benefits in introducing a new language as opposed to just using an existing one. I think a Rust that used automatic memory management would effectively be a new language. There would be all the costs that come with introducing a new language: new tooling (even if based on Rust tooling, it'd have to be heavily modified), bootstrapping an ecosystem and community, and so forth. While making new languages is awesome, we have our hands full with the one we have :)
Dyon in particular sounds interesting for realtime apps as it uses a lifetime checker instead of GC.
i also feel fracturing the community would be terrible. i came from basically a dynamic programming background (had done java and c++ in soft. eng. in school and that's it) and I had no problem learning rust.
It doesn't do exactly this, but it's similar I think.
GC is incredible productivity boost which is why no recent language (except Rust) does manual memory management.
Compile times in Go are a fraction of Rust compile times, which is another productivity boost.
Go gives you one good way to do concurrency, Rust believes in tyranny of choice.
Without mentioning that you don't paint the whole picture, just the parts that are favorable to Rust.
Rust was absolutely designed for programmer productivity. Source: I was one of the designers.
> GC is incredible productivity boost which is why no recent language (except Rust) does manual memory management.
That's true, it is a productivity boost. But it also has a cost. Rust didn't want to pay that cost, especially when the same mechanisms are useful for preventing data races. (In fact, removal of GC was something that happened as a consequence of the data race freedom features; it wasn't a design goal from the beginning.)
> Compile times in Go are a fraction of Rust compile times, which is another productivity boost.
And rustc performs much more optimization. Again, a tradeoff.
> Go gives you one good way to do concurrency, Rust believes in tyranny of choice.
That's untrue. Go has threads, channels, mutexes, condition variables, and atomics. Rust has threads, channels, mutexes, condition variables, and atomics. The only thing I can think of that Rust has that Go doesn't is, like, SIMD, and I'm sure your comment wasn't just referring to SIMD.
Here's where I would agree with you:
- Go makes it harder for someone to write overly abstract code (a common affliction!).
- Being able to occasionally do type assertions in an ergonomic way is surprisingly nice.
- I wish Rust had something in the stdlib like net/http.
- I like that go fmt is so unconfigurable and canonical.
Here's where I would disagree:
- I find ADTs (Rust's enums) super helpful for productivity.
- Removing nil pointer derefs is wonderful, particularly for refactoring.
- I spend too much time in Go rewriting bits of code that I would just use generics for in Rust or C++. Rust's iterators are wonderful and I end up using them over and over again.
- Maybe it's my C background, but I like being able to occasionally use macros. Even for tests it makes things much more readable.
- The borrow checker ends up moving many concurrency issues from runtime debugging to compile time debugging.
- I think cargo is more pleasant to use to manage code than using go + godeps/glide/etc.
Compile times are actually not that bad. I've seen some real doozies in my day, and plenty of hacks to overcome C++ compile times (distributed compiling, pre-compile steps to collect many dozens or more source files into a single TU, etc.). Rust is just fine. Besides, for the kinds of programs Rust is targeting being productive isn't synonymous with belting out as much code as fast as one can.
As for concurrency, I think having options is great. There is rarely a one size fits all solution for concurrency and having choice mirrors real use cases very nicely.
Furthermore I really enjoy generic programming. One of the worst parts of C is the lack of real generics. It gets tiresome writing the same array, hashtable, etc. code for each different type. Hiding it behind macros is terrible. It's one of many things that make both C++ and Rust superior to Go, in my view.
That said, I do perceive a certain "feature my preferred language offers is the most important thing ever" myopia about some aspects of the Rust community. It's similar to a certain segment of the C++ community zealously beating the drum of "performance, performance performance" to the exclusion of other important things. Rust hasn't the popularity or use in the wild for its warts to be exposed yet, but time will tell. Every language has flaws and proper (and improper) uses.
Are there different productivity levels between Go and Rust? Probably. But to say Rust wasn't "designed for programmer productivity" definitely isn't right from where I'm standing.
Swift is a recent high-level productive language without a GC.
Edit: I'm going to answer my own question here: yes. I just sometimes think Rust is a victim of its own success when people expect to learn Rust quickly because they learned Python in two days.
No one expects to master C++ in a weekend.
What's the value proposition for using rust over go?
At a language-level Rust has generics, a better Type system and is better suited to functional programming.
Seems Systems-level programming, High-performance computing and resource-constrained embedded devices are areas where Rust would shine over Go.
First Google result for "Rust vs Go speed": https://benchmarksgame.alioth.debian.org/u64q/compare.php?la...
Rust seems to perform significantly better on some workloads while Go outperforms it marginally in other ones (except reverse-complement where Go is almost 50% faster than Rust).
Edit: As for the other points you make – they are often subjective and I've read the opposite to your statement at least as often.
Productivity features like generics, a more mature optimization pipeline, freestanding (runtime-less use), highly optimized libraries like serialization frameworks and regular expressions, etc. etc.
https://en.wikipedia.org/wiki/Intel_iAPX_432
https://en.wikipedia.org/wiki/Intel_i960
https://en.wikipedia.org/wiki/Burroughs_large_systems#Tagged...
http://www.smecc.org/The%20Architecture%20%20of%20the%20Burr...
I'm sure there were similar design in the 1990s, but I don't have references ready off the top of my head like the above.
The day that Rust manages to have always up to date Qt bindings that do not force you to make compromises compared to the C++ API, I think the C++ support will be at a comfortable level. Right now there are fresh efforts in the Rust and Haskell camps to solve this cleanly in a modern way. It would certainly help if the consumption of C++ APIs via llvm (which is used a lot byt Rust) was made a first class feature like you can import and export C APIs. Exporting C++ classes is a whole different story and may not map in any reasonable way to Rust modules or crates.
I found the existing ones very helpful and instructive.
"The primary author ... and the narrator on the screencasts, is Nicholas Matsakis ... Niko has been involved in Rust since 2011 and is a member of the Rust core team as well as the leader of the language and compiler teams"
After using IntelliJ IDEA plugin [1] (works in free community version too), I don't understand what else people need :) Plugin is pretty powerful. Also Racer works great in VS Code and other editors.
> Rust should have a lower learning curve
Rust is easy enough to learn, the only issue is a steep start. After couple of months everything is not harder than JS and smart compiler actually makes me more and more lazy :) So I think only thing we need is books/articles to help people switch from other languages, to help them overstep initial difficulties.
I expected that to be higher actually, but that's still the only reason I don't use the language. I've come to rely heavily on IDEs. Whether right or not it's a huge factor in my decision to wait for the language.
They've also been making leaps and bounds in terms of features so I can only imagine it improving even more.
- Refactoring Support (rename variable, class, function)
- Code Folding
- Automatic type checking
- Automatic error detection (tells me when syntactical or other errors are made)
- Built-in documentation loading/display on hover of cursor.
- Same thing as above except with any documentation I add myself on a function.
- Debugger with comment overlay of values (like PyCharm)
- Dependency management/Building/Deploying all a *button* (not 10 commands) away
- VCS integration
- Automatic code formatting
- Automatic code "cleaner" (change for (int i = 0; i < arr.length; i++) to an expanded loop for example)
- Automatic import cleaning
- Automatic project creation for basic use cases (console, GUI, maybe a web framework)
- Change CWD/environment variable for running the program
- GOTO definition
- A Graphical User Interface (Graphical being the biggest requirement)
Outside of all of those, there is a much much much more important feature: Auto Complete. A smart auto complete. An autocomplete that understands the type system and the function's return types.For instance if I am typing:
String sub = someString.
It shouldn't recommend "length()" as well as in the case of: String lengthStr = Integer.toString(someString.
It should recommend things that return an integer. This needs to be fast and needs to be non-case-sensitive. Also, if I am typing Lis
It should recommend List, ArrayList, etc in that order with the closest thing up front. It should also in the recommendation screen show documentation, a link to official documentation, and possibly an example of how to initialize/use the code. If something isn't imported and so it's not currently usable, if the user clicks enter or whatever on the auto-complete screen you should import it. If it has that, and has that working quickly, and has that working completely it's a "real" IDE in my book. That list is just "wants", this one thing is a "need"If I had that for rust, I'd switch over to rust as my main language. Anything that doesn't have something like that will never compete with Eclipse in ease-of-adoption in my book.
>1 in 4: learning curve
>1 in 7: lack of libraries
>1 in 9: general “maturity” concerns
>1 in 19: lack of IDEs (1 in 4 non-users)
>1 in 20: compiler performance
>None of these obstacles is directly about the core language or std; people are generally happy with what the language offers today. Instead, the connecting theme is productivity—how quickly can I start writing real code? bring up a team? prototype and iterate? debug my code? And so on.
I don't really see how this conclusion was reached from that data. The "learning curve" is almost certainly a reflection of the language being a little esoteric and the demands of the borrow checker. And "lack of libraries" is partly a comment on the ecosystem, but also partly shows that std is obviously lacking for some needs. Finally, "general maturity concerns" refers to worries that the language or std will keep changing, as is assumed they have not been perfected yet.
Those are the top 3 concerns and to me, both seem to relate directly to the language or standard library.
For more details, see: https://doc.rust-lang.org/std/marker/trait.Sync.html and https://doc.rust-lang.org/std/marker/trait.Send.html
When I look at this :
"Production use measures our design success; it's the ultimate reality check. Rust takes a unique stance on a number of tradeoffs, which we believe to position it well for writing fast and reliable software. The real test of those beliefs is people using Rust to build large, production systems, on which they're betting time and money."
I see a little bit of haste towards production use. From 'Rust 1.0 is out just last year' to 'We really need successful production use', It does some to be a push from management to justify continued investment in Rust project.
I've updated the RFC to clarify this; thanks for the comment!
It has nothing to do with management and justifying investing in rust. We are fortunate that Mozilla invests in rust to use rust and is currently very happy doing so.
Yes, please. I get better every day with Rust. I'd ask that the docs on lifetimes be improved with more elaboration on the ideas and more examples. Frankly, I still find the details confusing, so I can't offer more particulars right now.
Second it would be nice to see some best practices not just for libraries but application development. What to do and what not to do. Maybe a cookbook or even... design patterns. I had a hard time trying to figure out if I should embrace closures or go traits (at the time closures were not working as well so maybe this is not an issue either).
I would love to see such a thing as well; I wonder if we're not quite old enough to have said patterns really gel yet. We'll see if someone comes up with something.
As long as you split your code into goroutines, you just treat IO as synchronous, while it's actually async underneath.
Lua also has very clean and elegant bindings to C. Lua is designed to be implemented in strict ISO C, yet also to make the C API a first-class citizen--not a hack around the VM like Python, Ruby, etc. The one caveat to this equivalence is coroutines--when a coroutine yields and resumes, it can't revive any C invocation frames (e.g. when Lua calls C calls Lua). So the C API to invoke a Lua routine can take a callback and cookie. If the VM yields and then resumes a coroutine across a C API boundary, the "return" from the Lua routine invocation happens by invoking the C callback. (See lua_callk in the manual.)
From the perspective of C, as well as the kernel, this is a classic asynchronous I/0 pattern. From the perspective of Lua-script code, everything is transparent.
I take it that because Go implements light-weight threads (goroutines, which is likely a pun on coroutines) you do not perceive it as offering async I/O. And yet from the perspective of the implementation as well as the kernel it's classic async I/O using epoll or kqueue, whether goroutines are bound to a single CPU core or not. The send and receive operations on a Go "channel" are very similar to the resume and yield operations of classic routines, and semantically identical in the context of async I/O programming (because with both goroutines and async I/O there are no guarantees about the order of resumption).
Do you equate async I/O with callback-style programming? Do you think callback-style is somehow intrinsically less costly in terms of CPU or memory? I would dispute both of those contentions.
It would be really nice with a way to slowly start writing code in Rust instead.
I know the list isn't necessarily prioritized, but these 3 feel backwards.
A good IDE will provide can help facilitate easier edit/compile/debug cycle which makes learning the language faster because it's cheaper (time wise) to figure things out.