Hi there, Rustographers.
The Rust webpage needs one or more better examples, and we need your help to make them.
From the issue tracker the current idea is that we might replace the existing example that tries to stuff as many concepts into as few lines as possible, with several simple examples.
So, per @alilleybrinker's comment, let's come up with simple examples along the following lines:
- Zero cost abstractions: I like the idea of showing off iterators, as they are one of the most common abstractions in Rust code, and they nicely embody this particular design goal.
-
Move semantics: This one is difficult, because there is a question of how much we want to include. We can go all out and make it about how everything is moved by default, unless it implements
Copy
, or as simple as showcasing what a move is in Rust. I am not sure here. If it's something aboutCopy
it could be along the lines of defining two structs, both containing ani32
, one of which implementsCopy
while the other doesn't, along with an example assignment for both of them. -
Guaranteed memory safety: The first thing to look at here is exactly what is meant by memory safety. Per the Rust language reference, Rust promises that no code will do the following, which is guaranteed by the compiler for safe code, and assumed to be checked by the programmer for unsafe code. Any example should likely showcase the inability to do any of these three things.
- Dereference a null/dangling raw pointer
- Read undef (uninitialized) memory
- Break the pointer aliasing rules with raw pointers (a subset of the rules used by C)
- Threads without data races: There is a lot of good stuff to work with here, with a lot already written about Rust's excellent systems for concurrency. We can likely build off prior work quite easily.
-
Trait-based generics: Once again, it should be pretty easy. Likely best to take a trait that already exists, define a struct and implement that trait for that struct, and then use a primitive type and the struct in a function provided by that trait.
Add
would be a pretty straightforward one. - Pattern matching: I like your idea, and can't think of anything better.
- Type inference: Lots of good options here. We likely want to make it clear that types can be inferred even in a lot of complicated places, and that types are only mandatory in function signatures (or where there is an ambiguity that can't be resolved without an annotation).
- Minimal runtime: I am not sure this can be shown in a static code example. This may be something best left to the book.
- Efficient C Bindings: C bindings are important. Rust's ability to very easily interoperate with C code is a major selling point. We can likely adapt something from the book here.
I'll start:
Zero-cost abstractions:
fn main() {
// Closures have stack-allocated environments
// and are statically-dispatched.
let offset = 10;
println!("{}", [1, 2, 3].map(|x| x + offset));
}