# Rust cheatsheet

Rust is a relatively new programming language, and it's already a popular one [winning over programmers](https://opensource.com/article/20/5/rust-java) from all industries, but it's also a language that builds on everything that's come before.
Rust wasn't made in a day, after all, so even though there are concepts in Rust that seem wildly different from what you might have learned from Python, Java, C++, and so on, they all have a foundation in the same CPU and NUMA architecture you've always been (whether you know it or not) interacting with.
I'm not a programmer by trade.
I'm impatient, yet obsessive.
If a language doesn't help me get the results I want relatively quickly, I rarely find myself inspired to use it when I need to get something done.
Rust tries to bring into balance two conflicting things: the modern computer's need for secure and structured code, and the modern programmer's desire to do less work while attaining more success.

## Install

The [rust-lang.org](http://rust-lang.org) website has great documentation on installing Rust, but usually it's as simple as downloading the `sh.rustup.rs` script and running it.

```bash
$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs
$ less sh.rustup.sh
$ sh ./sh.rustup.rs
```

## No classes

Rust doesn't have classes, and does not use the `class` keyword.
Rust does have the `struct` data type, however, and its purpose is to serve as a kind of template for a collection of data.
So instead of creating a class to represent a virtual object, you can use a struct:

```rust
struct Penguin {
   genus: String,
   species: String,
   extinct: bool,
   classified: u64,
}
```

This can be used similar to how a class is used.
For instance, once a `Penguin` struct is defined, you can create instances of it, and interact with that instance:

```rust
struct Penguin {
   genus: String,
   species: String,
   extinct: bool,
   classified: u64,
}

fn main() {
   let p = Penguin { genus: "Pygoscelis".to_owned(),
        species: "R adeliæ".to_owned(),
        extinct: false,
        classified: 1841 };

   println!("Species: {}", p.species);
   println!("Genus: {}", p.genus);
   println!("Classified in {}", p.classified);
   if p.extinct == true {
       println!("Sadly this penguin has been made extinct.");
   }

}
```

Using the `impl` data type in conjunction with the `struct` data type, you can implement a struct containing functions, and you can add inheritance and other class-like features.


## Functions

Functions in Rust are a lot like functions in other languages.
Each one represents a discreet set of tasks that you can call upon when needed.
The primary function must be called `main`.

Functions are declared using the `fn` keyword, followed by the name of the function, and any parameters the function accepts.

```rust
fn foo() {
 let n = 8;
 println!("Eight is written as {}", n);
}
```

Passing information from one function to another is done with parameters.
For instance, I've already created a `Penguin` class, and I've got an instance of a penguin as `p`, so pass the attributes of `p` from one function to another requires me to specify `p` as an accepted `Penguin` type for its destination function.

```rust
fn main() {
 let p = Penguin { genus: "Pygoscelis".to_owned(),
   species: "R adeliæ".to_owned(),
   extinct: false, classified: 1841 };
 printer(p);
}

fn printer(p: Penguin) {
 println!("Species: {}", p.species);
 println!("Genus: {}", p.genus);
 println!("Classified in {}", p.classified);
 if p.extinct == true {
     println!("Sadly this penguin has been made extinct.");
 }
}
```

## Variables

Rust creates immutable variables by default.
That means that a variable you create cannot be changed later.
This code, humble though it may be, cannot be compiled:

```
fn main() {
let n = 6;
let n = 5;
}
```

However, you can declare a mutable variable with the keyword `mut`, so this code compiles successfully
```
fn main() {
let mut n = 6;
println!("Value is {}", n);
n = 5;
println!("Value is {}", n);
}
```

## Compiler

The Rust compiler, at least in terms of its error messages, is one of the nicest compilers available.
When you get something wrong in Rust, the compiler makes a sincere effort to tell you what you did wrong.
I've actually learned many nuances of Rust (insofar as I understand any nuance of Rust) just by learning from compiler error messages.
Even when an error message is too obscure to directly learn from, it's almost always enough for an Internet search to explain.

The easiest way to start a Rust program is to use `cargo`, the Rust package management and build system.

```bash
$ mkdir myproject
$ cd myproject
$ cargo init
```

This creates the basic infrastructure for a project, most notably a `main.rs` file in the `src` subdirectory.
Open this file and paste in the example code I've generated for this article:

```rust
struct Penguin {
   genus: String,
   species: String,
   extinct: bool,
   classified: u64,
}

fn main() {
   let p = Penguin { genus: "Pygoscelis".to_owned(), species: "R adeliæ".to_owned(), extinct: false, classified: 1841 };
   printer(p);
   foo();
}

fn printer(p: Penguin) {
   println!("Species: {}", p.species);
   println!("Genus: {}", p.genus);
   println!("Classified in {}", p.classified);
   if p.extinct == true {
       println!("Sadly this penguin has been made extinct.");
   }
}

fn foo() {
    let mut n = 6;
println!("Value is {}", n);
n = 8;
 println!("Eight is written as {}", n);
}
```

To compile, use the `cargo build` command:

```bash
$ cargo build
```

To run your project, execute the binary in the `target` subdirectory, or else just use `cargo run`:

```bash
$ cargo run

Species: R adeliæ
Genus: Pygoscelis
Classified in 1841
Value is 6
Eight is written as 8
```

## Crates

Much of the convenience of any language comes from its libraries or modules.
In Rust, libraries are distributed and tracked as "crates".
The [crates.io](https://crates.io/) website is a good registry of community crates.

To add a crate to your Rust project, list them in the `Cargo.toml` file.
For instance, to install a random number function, I use the `rand` crate, with `*` serving as a wildcard to ensure that I get the latest version at compile time:

```rust
[package]
name = "myproject"
version = "0.1.0"
authors = ["Seth <[email protected]>"]
edition = "2022"

[dependencies]
rand = "*"
```

Using it in Rust code requires a `use` statement at the top:

```rust
use rand::Rng;
```

Some sample code that creates a random seed, and then a random range:

```rust
fn foo() {
   let mut rng = rand::thread_rng();
   let mut n = rng.gen_range(1..99);

   println!("Value is {}", n);
   n = rng.gen_range(1..99);
   println!("Value is {}", n);
}
```

To run it, you can use `cargo run`, which detects the change in code and triggers a new build.
The build process downloads the `rand` crate and all the crates that it in turn depends upon, compiles the code, and then runs it:

```rust
$ cargo run
   Updating crates.io index
 Downloaded ppv-lite86 v0.2.16
 Downloaded 1 crate (22.2 KB) in 1.40s
  Compiling libc v0.2.112
  Compiling cfg-if v1.0.0
  Compiling ppv-lite86 v0.2.16
  Compiling getrandom v0.2.3
  Compiling rand_core v0.6.3
  Compiling rand_chacha v0.3.1
  Compiling rand v0.8.4
  Compiling rustpenguin v0.1.0 (/home/sek/Demo/rustpenguin)
   Finished dev [unoptimized + debuginfo] target(s) in 13.97s
    Running `target/debug/rustpenguin`
Species: R adeliæ
Genus: Pygoscelis
Classified in 1841
Value is 70
Value is 35
```

## Rust cheatsheet

Rust is a supremely pleasant language.
It feels appropriately modern, thanks to its integration with online registries, its helpful compiler, and its almost intuitive syntax.
Make no mistake, though, it's also a complex language, with strict data types, strongly scoped variables, and many builtin methods.
Rust is worth looking at, and if you're going to explore Rust, then you should download our [free Rust cheat sheet](LINK TO THE CHEATSHEET) so you have a quick reference for the basics.
The sooner you get started, the sooner you'll know Rust.
And, of course, you should practice often, to avoid getting rusty.