443 points · by steveklabnik · 10y ago · 216 comments
C11 (and C++11) defined a memory model and atomic operations for shared-state lock-free concurrency. But that model and the atomic operations aren't being used by Linux, because they didn't match up with the semantics of the operations that Linux uses. (See https://lwn.net/Articles/586838/ and http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p012...).
I'm curious what Rust says about this. Does Rust have a memory model like C11/C++11? I'm curious whether Rust (and C11/C++11 for that matter) will evolve to have primitives like what the Linux kernel currently defines and uses.
https://github.com/rust-lang/rfcs/issues/1447 is a good thread if you care about this topic.
As part of defining the Rust semantics they will certainly tackle the question of the memory model. Dreyer and company have a track record of providing semantics and reasoning principles for weak memory models (like C11).
You might have to wait a while for a rigorous semantics though.
The Linux kernel is written in C, but uses lots of GCC-specific features and inline assembly to address things that aren't covered by the C standard. Among these, the Linux kernel has its own set of atomic types and memory barriers. It documents them here: https://www.kernel.org/doc/Documentation/memory-barriers.txt
So even if Linux is being compiled on a conforming C11 compiler (the Linux kernel is written in C, not C++), it uses its own atomic primitives instead of the ones provided by the language. Hope that helps.
As the HN crowd seems to have quite a lot of Rust supporters, would it be a good selling point in a job description ?
i.e if (it's just currently a personal hypothesis) a company were to consider to (re)write some part of its Rest-ish microservices and that Rust was the chosen language, and was looking for people to help on that, would it make a `interesting++` in your mind ? for real services used by real people by a not-so-startup company, in europe.
edit: I already deployed in production for my previous company some (with a very stricly limited scope) microservices in rust (with everyone approval) and it was quite a success, so I'm more and more thinking that rust is now enough developed to fit the market of language for microservices, as it's more or less "understand HTTP, read/write from redis/postgresql/mysql/memcache, do some transformation in between" and Rust now support these operations quite well
Yes it would. People love to be trained on a new software stack at someone else's expense, especially if they're not having to take a seniority hit to go there.
Also, since you mentioned PostgreSQL, if you can make the db handle json the shuffling part should be really trivial. Give node.js + pg-promise a spin for comparison.
But then again, I haven't used Rust for anything serious, so am happy to be wrong.
1. rust handle erros in a VERY expressive way, and I do want my services to log ANY errors, and to be sure to miss any (kind of like what go permits too , but Rust Errors are more flexible) , so with rust it's hard to forgot a case of error and finished with "errr my API did a 500 but i don't know why"
2. It's a (nearly) self contained binary with low memory overhead, I can have dozen of microservices like this on my workstation / CI environments without making the machine cries So I can deploy it on cloud provider X or workstation Y without needing to worry if it has the version of node / python / php I need
3. it creates very small docker image if you're using docker (so it beats node/python/php here)
4. if I want to make my services multi-threaded and have some internal cache for some reason I'm sure the compiler will not let me create concurrent access problem that I would otherwise only detect in production when it's too late (beats every other languages , including go , the go race detector of go is nice, but it's at runtime so not the same league)
5. no nil pointer exception things (beat other languages here too)
6. strong typing but flexible (no go, I don't want to cast everything in {}interface everytime i need to make things a bit more generic, though I know it's just a personnal opinion), because no I don't want my developer to either develop a "is_true" function , or worst to rely on type casting for if to work.
7. the compiler as my first set of test it's a whole category of things you don't need to write test for because it's already handled by the compiler.
8. highlevel when you needs, low level when you want, I know that the language is not my bottleneck (or then I've reached the point where I don't care because my system is performant enough) , but if I need to serialize my struct into a json, I can in some line of codes.
9. plenty other little things , like scoping variables, immutable by default , possibility to have your SQL request check at compile time if you use postgresql plugin, using first-class debuggers to do step by step if you need , interfacing with C libraries pretty easily
But, you could write embedded software, device drivers and even operating systems in Rust, that's the domain where Rust could and hopefully will dominate.
http://stevehanov.ca/blog/index.php?id=95
It's a bit silly, but I do think that Rust could be a very good solution here. For one thing, in my experience it is much easier to write than C++, especially for something you'd feel comfortable pointing at users.
It would be cool to see some articles that are the reverse of "scale all the things," something like "sympathize with all the caches."
This is the classic domain of scripting languages (PHP, Ruby, node, ...), where a huge ecosystem exactly for this kind of tasks exists. But yes, type safety and error handling is not the best there.
If a good type system and a good ecosytem is desired then F# or a JVM language (Scala with Play Framework, Kotlin, ...) could be used, which would from my perspective give a more productive setup for this task.
I don't want to say that Rust is not good, but (just like C++) I think it's best use cases are other applications then webservers, e.g. high performance audio and video processing or bare metal software.
But honestly, even if I hadn't it's be a selling point to me because it tells me that you're a place that isn't stuck writing everything in a single language but are willing to try new things are willing to use what seems to be the right tool for the job.
Because he doesn't like NULL pointers aka the worst mistake of CS?https://www.lucidchart.com/techblog/2015/08/31/the-worst-mis...
Because he doesn't want a package manager that always fetches HEAD?
I'm not saying Go is a poorly designed language where the answer to every decision is the easiest one for the implementors. I'm just saying there's a legitimate case to be made.
I cross-compiled this stuff to run on Raspberry Pi, and the binaries are so small and performant!
Feel free to respond here or reach out (contact details in my profile, you can find me as reem on the mozilla irc network).
This isn't the case. We have web backend libraries (servers, database thingies, template engines, I/O, etc) and it's totally possible to work on backend stuff in Rust. Rust doesn't "not target" much, really. Most of what you do in Python/Go/Ruby is also something we want Rust to work for. There is a false dichotomy of "fast language or safe language" which Rust does away with -- it's not only for situations where you would usually use C++.
It feels odd that someone would question it nowadays.
I surely do hope Rust gets used for everything.
What do you mean by `doesn't target backend app'?
more reasons:
On error handling, in Go most of libraries and even some part of the std lib, erros are constant string, which mean that for example you can only do
`err == foo.DUPLICATE_KEY_ERROR`
but you can't extract which key, or then you start to have to either use an external library to do some string masking/unmasking, which complicate quite things and add one more dependency, or just to say "screw it, i will just log 'duplicate key error" which is unoptimal
I really did try go, to the point I even proposed a fix in the std library for a long standing bug in the xml library https://go-review.googlesource.com/#/c/15684/ , but not all the reason stated above makes me consider go as "yes sure it's an improvement over php/python/c++" but rust is like an even bigger improvement
As I got more into this kind of language I found that the language tools gave me very strict isolation, which lowered the value of separating everything at the process level. So I've shifted towards a more monolithic style of architecture.
You can follow along, all slides and HW are on github.
They probably should have prepended the school name to their GitHub org, but that's just my 2 cents :)
"Actually managed to sneak some Rust into production."
"...sneak some Rust..."
"...sneak..."
There's your answer on that one. ;) Others might be quite useful, though.
I Work in an aging framework for electronics testers written in a combination of C#/VB/LabVIEW its highly asychronous nature make debugging the system an issue.
Likewise, Rust is not finalized as a language yet. That means whoever has to maintain the original commenter's code is likely to be in for a rough time if and when they ever attempt to bump the Rust version.
I actually find myself pining for the simplicity of #[test] in other languages. It makes the Write->Test->Write loop so much faster.
For those wondering, stable just meant the API defined for interactions with some libraries were subject to change. It wasn't like a problem with using the APIs, it was just the developer has to know that new releases might change how they worked or if they would even be available in the future.
For network stuff I used openssl[0] and std::TcpStream [1]
I didn't use a GUI. I plan on using piston.rs[2] to build games but there are Qt, GTK+ and even Cocoa integrations for rust.
[0] https://crates.io/crates/openssl/
In terms of networking, I threw together a working console IRC client in about 60 lines of Rust (using standard library threads and TcpStreams). And I'm very much a Rust beginner. And Rust forced me to consider error handling in a way I wouldn't have otherwise.
I should also say that the community is unusually supportive: I've asked some questions on the IRC channel and got really helpful replies (and haven't noticed any of the snark that comes with a lot of IRC channels).
irc client: Everyone's least favorite Gtk project. For whatever reason, at one time there were seven active projects to develop a Gtk irc client. Used to deride poor judgement in choosing projects or lack of knowledge about what's going on. Often used self-deprecatingly, as in "I know, I'll write an irc client."
Thanks for keeping the dream alive.
An IRC bot is a great way to learn a new programming language. You have to learn how to use threading or asynchronous operations to get multiple connections, you have to learn how to use TLS for secure connections, you have to learn how to manipulate strings, how to read configuration files. It's a super good project for learning.
I use Rust for web as REST API and I'm absolutely in love with this language. Maybe first steps were little bit steep, but it's worth it :)
// cargo run!
[dependencies.iron]
version = "0.2.*"
[dependencies.bodyparser]
git = "https://github.com/iron/body-parser.git"
[dependencies.redis]
git = "https://github.com/mitsuhiko/redis-rs.git"
[dependencies]
router = "*"
rustc-serialize = "*"
plugin = "*"
rand = "*"
toml = "*"
rust-crypto = "^0.2"
hyper = "*"
r2fa = "*"
urlencoded = "*"
regex = "*"
[dependencies.mysql]
default-features = false
features = ["socket"]
And soon here will be added "rusoto". [dependencies.redis] git = ...
is the same as [dependencies] redis = { git = ... }
This will let you have just one [dependencies] block, which is a bit nicer looking. I've been changing examples to use it instead of that older style; they're equivalent if you prefer it though.For now.
Furthermore, you can use a no_std library with an application that uses std just fine. The use case not quite covered is "I want an application with no standard library at all, period."
What two specific items? By "lang item" here, do you mean roughly "symbol", or something else entirely?
The two lang items that are absolutely required but not defined in core are 'eh_personality' and 'panic_fmt'. Read more here: http://doc.rust-lang.org/nightly/book/no-stdlib.html
$ cargo new example --bin
$ cd example
$ cat > src/main.rs
#![no_std]
fn main() {}
^D
$ multirust run stable cargo run
Compiling example v0.1.0 (file:///home/steve/tmp/example)
error: language item required, but not found: `panic_fmt`
error: language item required, but not found: `eh_personality`
error: aborting due to 2 previous errors
Could not compile `example`.
In general a "lang item" is some portion of Rust that the language expects to be defined in some manner. They must all be defined for compiling to work. `libcore` defines many of these language items, but does not for these last two. `libstd` does.You can provide your own:
#[lang = "eh_personality"]
extern "C" fn eh_personality() {
}
#[lang = "panic_fmt"]
fn panic_fmt() -> ! {
loop {}
}
These are enough to get going, but actually using `#[lang]` requires a `#![feature]`, which requires nightly.You also end up needing #[start], which is also behind a feature gate. The documentation brson linked you to contains an example no_std executable.
That flag you refer to exists, it's #![feature].
https://crates.io/crates/rusoto/
Haven't tried it yet (backwaters don't usually look kindly on AWS :) ), but that looks like what you're talking about. There are a ton of libraries for Rust these days (relative to the amount of time since 1.0, at least).
(For those not familiar: the libc crate went from 0.1 to 0.2. Many people were depending on libc="*". Cargo allows for multiple copies of a library with incompatible versions. But the releases were incompatible for a reason... it caused problems. This fix is one of the things we're doing to address it, there's more coming in the future.)
The Rust standard library feels so much more modern and easy to use than the STL. The documentation is fantastic, too.
C++ pointers, casting, OO, templates, and all the billion other language features feel like traversing down a rabbit hole. Rust is small enough to grok in a day. The syntax is incredibly expressive and a joy to use.
I would say it is far easier to learn how to write good systems code in Rust than C++, but saying you can grok it in a day is a bit optimistic. On the surface level, perhaps. But the semantics of the type system can take longer to internalise, depending on one's background.
Don't forget your & in your function declaration or you'll silently copy objects.
Don't forget to make your destructor virtual in your base class (don't forget to add it if the class wasn't originally going to be a base class!) or you get fun crashes on delete every once in a while.
Use "explicit" with your one-parameter constructors to avoid fun with automatic conversions.
std::string is practically useless
Use "." with classes/structs/references and "->" pointers (why am I the compiler?!)
Think you know what "a = b;" does? Think you know what the =,==,!=,<,>,^,,+,-,/,=,+=,-=,/=,^= operators do? Not unless you checked to see if someone override them!
Ever tried to read some code that uses templates?
If you declared Class(int x) and Class(char x) and then do Class('a'), it silently gets constructed with the integer version (or maybe it's with Class(const char x), can't remember, which should say something right there.)
Quick, what does "const int
const x;" mean?Quick, what does "int* a, b;" do, and is that what you expected?
Is it safe to do "a = b"? You don't know until you read through all the class hierarchies to see if the object has a pointer, and if so, if it has an assignment operator that works properly ("properly" being somewhat relative to the purpose of your object).
Fun times debugging stuff like
if (...)
statement1;
statement2;
Can you call a virtual function from a constructor? Which version of C++ are you using?I have a soft spot in my heart for C++, but boy is there a lot to remember, and the mistakes/typos can kill a good half-day, minimum. I'm excited for the day I have a project I can use Rust on, looking forward to something I don't have to be always on my guard with!
> Don't forget your & in your function declaration or you'll silently copy objects.
I think this still exists in Rust to a limited extent but it's mitigated:
* Rust uses move semantics by default, so unless the type was specifically marked as Copy[0] it will be moved into the function which should be noticeable
* references are actual types, `&Foo` can't be confused with `Foo` and (outside of method receivers) references are created explicitly, so the callsite knows whether it's passing a reference
> Don't forget to make your destructor virtual in your base class (don't forget to add it if the class wasn't originally going to be a base class!) or you get fun crashes on delete every once in a while.
Rust has almost no inheritance support, and the realms of static and dynamic dispatches are pretty well separated (trait objects are dynamic, the rest is mostly static) so that should not be an issue.
> Use "explicit" with your one-parameter constructors to avoid fun with automatic conversions.
Rust has very little implicit behaviour (auto-deref is the main one I think), and I don't think it has implicit/automatic conversions.
> std::string is practically useless
Without more information as to its failing, I can't say whether String (and &str) is more useful. IME it certainly is useable and useful.
> Use "." with classes/structs/references and "->" pointers (why am I the compiler?!)
Yup, this is done through auto-defer (of types implementing the relevant trait of course), though it does have a separate `::` for other context.
> Think you know what "a = b;" does? Think you know what the =,==,!=,<,>,^,,+,-,/,=,+=,-=,/=,^= operators do? Not unless you checked to see if someone override them!
Can't override assignment itself, you can override other operators[1] and there is an accepted RFC for overloading augmented assignments[2]. Though these overrides are trait-based which should limit the shenanigan space somewhat.
> Ever tried to read some code that uses templates?
Rust's generics are slightly simpler, but they're lacking features (no template specialisation currently) so… not sure.
> If you declared Class(int x) and Class(char x) and then do Class('a'), it silently gets constructed with the integer version (or maybe it's with Class(const char x), can't remember, which should say something right there.)
See item above, the very declaration doesn't exist in Rust, you'd need to have two separate factory functions.
> Quick, what does "const int const x;" mean?
Should be clearer in rust, type declarations are fairly regular.
> Quick, what does "int* a, b;" do, and is that what you expected?
I think that's equivalent to `int* a; int b`?
Type information is an optional postfix addendum in Rust, so the ambiguity doesn't exist, but if you want explicit types you don't get the convenience of shortened declaration. The closest to this code would be
let (a, b): (Box<u32>, u32)
which isn't much of a gain over let a: Box<u32>;
let b: u32;
if you're not unpacking an existing structure> Is it safe to do "a = b"? You don't know until you read through all the class hierarchies to see if the object has a pointer, and if so, if it has an assignment operator that works properly ("properly" being somewhat relative to the purpose of your object).
See above, assignment itself can't be overloaded (at least at the moment)
> Fun times debugging stuff like
I think the only places where braces are optional in Rust are non-ambiguous 1-expression lambdas (`|| {expr}` can be written as `|| expr`) and 1-expression match arms e.g.
match foo {
v1 => { expr1 },
v2 => { expr2 },
}
can be written match foo {
v1 => expr1,
v2 => expr2,
}
> Can you call a virtual function from a constructor?Rust doesn't have constructors so no. As for the intent, since Rust doesn't have constructors you can't have partially built values (unless you forcefully partially build them) so the answer should still be no.
[0] http://doc.rust-lang.org/std/marker/trait.Copy.html
Rust does have a lot of features, but for most programming often you don't have to dabble in the more advanced features, which is great. Whilst working on Servo I mostly stuck to the basic features which I was familiar with for a long time and only learned the complicated stuff after a few months out of interest.
One major difference is that Rust forces you to learn about ownership and borrowing up front. This is cognitive load you would have to take in any systemsy language at some point when learning about memory management, Rust just makes you learn it early.
So, it allows you to have safety and control. I thought that is very neat.
I've got three questions for experts. One, what type of applications is Rust intended for?
Two, I like JS because I can code in the client, and server in one language. Will there ever be a web server framework for rust and an api that allows me to modify the dom?
Three, what are your predictions for the future of rust?
2. There are already several web frameworks, in various stages of earliness. See [1]. I don't think it will ever be a good idea to write Rust client-side though (even though I believe there is an emscripten backend for it, so it's possible).
3. I see a very bright future for Rust. It could use some ergonomic improvements (but it's miles ahead of C++ even now, mind you), but is otherwise a very well designed language that fits very snuggly in its niche. And it has some very strong backing from Mozilla. I expect it will slowly take over large amounts of territory from C++ and possibly from C, as these developers start to realize the benefits of Rusts safety guarantees. It's also quite unique in that its safety entices many higher-level (python, ruby, C# etc.) developers into trying system programming, which could be really transformative to the system programming scene. For example, one thing that has already come out of this is the cargo package manager, which is similar to npm, bundler etc. but (before cargo) had yet to find its way down to the lowly systems programmers. Many (former?) C++ developers actually tout it as one of the major benefits of Rust.
Do note that, for many things on the web, JavaScript is PLENTY fast. It's when you are doing crazy things like CAD in the browser, it'll be amazing.
I have several crates providing access to GPIO/SPI/I2C under Linux and would like to put together a roadmap for having the interface to these types of devices that is portable to various platforms and devices (e.g. Linux as well as Zinc, ...).
The native thread/connection model quickly shows its limits, and is very slow on virtualized environments.
mio is as low-level as libevent and just as painful to use.
mioco and coio are very nice but blow the stack after 50k coroutines.
But for web services? I think it is overkill. I think Go strikes a nice balance. I would love to be convinced otherwise though. So please tell me, what am I missing?
- no need to copy-paste code for generic algorithms
- proper dependencies management