presentation-rust-introduction/rust-intro.org
2021-09-27 14:56:38 +02:00

19 KiB

∈cludesvg[height=.25\textheight]{img/rust-logo-blk}≠wline An introduction to Rust

Rust

Abstract

#+LaTeX:∈cludegraphics[width = 0.5\textwidth]{img/Bruine_roest_op_tarwe_(Puccinia_recondita_f.sp._tritici_on_Triticum_aestivum).jpg} 4

Rust, the language

  • First appearance 2010
  • Memory safe without gcing, optional reference counting
  • Ownership, lifetimes, traits, functional paradigms
  • Variables are immutable by default and can be shadowed
  • Performance of idiomatic Rust is comparable to the performance of idiomatic C++
  • A well designed language and ecosystem

Strengths and Weaknesses1

Things Rust does measurably really well (Strengths)

Strengths and Weaknesses2

Points you might run into (Weaknesses)

  • Steep learning curve6 compiler enforcing (esp. memory) rules that would be "best practices" elsewhere.
  • Missing Rust-native libs in some domains, target platforms (esp. embedded), IDE features.6
  • Longer compile times than "similar" code in other languages.67
  • No formal language specification, can prevent legal use in some domains (aviation, medical, …).8
  • Careless (use of unsafe in) libraries can secretly break safety guarantees.

Problems and security Rust tries to conquer

#+LaTeX:∈cludegraphics[width = 0.8\textwidth]{img/compiler_complaint.png} 9

  • Dangling pointers / memory safety
  • Iterator invalidation
  • Thread safety / concurreny
  • Segfaults
  • Error handling
  • Zero-cost abstractions

Where to start?

First Steps

Other helpful sites

Where to find help and stay up to date

Language

  • Semicolons have meaning
  • Mutability
  • Shadowing
  • Functional paradigms

Mutability and shadowing

Immutable variable

let foo = 5;

Mutable variable

let mut bar = 5;
bar = 6;

Shadowing

let baz = 5;
let baz = baz + 3;

Type aliases

Tuple structs

Definition of a tuple struct

struct Rectangle(usize, usize);

Instantiation of a tuple struct

let rect = Rectangle(3, 5);

Access of a tuple struct's field

rect.0;
rect.1;

Structs

  • Direct access vs. getter and setter
  • Something::new(item) and Something::default()

Definition of a struct

struct Something {
    id: usize,
    item: String,
}

Error related types

  • Heavy use of Option<T> and Result<T, E>

Option

pub enum Option<T> {
    None,
    Some(T),
}

Result

pub enum Result<T, E> {
    Ok(T),
    Err(E),
}

Error handling

Unrecoverable errors → panics

fn get_data() -> Data {
    ...
    panic!("Cannot get data");
}

Recoverable error with anyhow

fn get_data() -> Result<Data> {
    ...
    Ok(data) // return is only used for "early" returns
}
...
    let data = get_data()?;
...

Use functional language features

  • vec![1, 2, 3].iter()
  • vec![1, 2, 3].iter().sum()
  • vec![1, 2, 3].iter().map(|x| x + 1).collect()
  • foo.into_iter().filter(|i| i.bar == 0).collect()
  • Iterator trait

Control structures

  • if, if let, match
  • loop, for, map()

Tests

  • Use assert!() family
  • Unit tests

    • Put them into a test module
    • Annotate the test module with #[cfg(test)]
    • Annotate the tests with #[test]
  • Documentation testing
  • Integration testing

    • Integration tests are put into the src/tests/ directory

Documentation

FFI (Foreign Function Interface)

Cargo

Cargo

\Huge Cargo

/finga/presentation-rust-introduction/media/commit/72b4170f1a39dfa93716dfef0a99f7c214c9ea7d/img/cargo.png

What is it?

  • Package manager
  • Cargo calls rustc, the Rust compiler
  • Build tool
  • A Cargo project contains at least one crate

Hello, World

Executing `cargo new foobar` creates a new project…

foobar/Cargo.toml

[package]
name = "foo"
version = "0.1.0"
authors = ["finga <finga@onders.org>"]
edition = "2018"

\tiny

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

\normalsize

[dependencies]

foobar/src/main.rs

fn main() {
    println!("Hello, world!");
}

Docs

Cargo commands/plugins

What I typically use

  • audit: Audit Cargo.lock for security vulnerabilities.
  • bloat: Identify which dependency adds how much bloat.
  • checkmate: Run a list of checks (check, format, build, test, doc, audit).
  • clippy: Linter and static code analysis.
  • deb: Automatically create a Debian package.
  • flamegraph: Generate flamegraphs about anything.
  • fmt: Format Rust code according to style guidelines.
  • install-update: Keep all your Cargo commands up to date.

Cargo downloads your Rust package's dependencies, compiles your package, makes distributable packages, and uploads them to crates.io, the Rust community's package registry.

The Rust (package) registry

Official registry

Unofficial crates.io frontend

lib.rs same but different..

Docs

Setup

Install the Rust-Toolchain

Install Rust

From rustup.rs: $ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Rustup: The Rust toolchain installer

  • Check for new versions: $ rustup check
  • Update the toolchain: $ rustup update
  • Update rustup itself: $ rustup self update
  • Install Rust nightly (daily builds): $ rustup toolchain install nightly
  • Activate nightly globally: $ rustup default nightly
  • Activate nightly locally (in current dir): $ rustup override set nightly

Handle the Rust toolchain with rustup

Install the Rust toolchain (rustup.rs)

$ curl --proto '=https' --tlsv1.2 -sSf \
  https://sh.rustup.rs | sh

Update rustup

$ rustup self update

Check for updates for installed toolchains

$ rustup check

Update toolchains if outdated

$ rustup update

IDE support

Are we IDE yet?3

\tiny

\rotatebox{90}{Syntax highlightning (.rs)} \rotatebox{90}{Syntax highlightning (.toml)} \rotatebox{90}{Snippets} \rotatebox{90}{Code Completion} \rotatebox{90}{Linting} \rotatebox{90}{Code Formatting} \rotatebox{90}{Go-to Definiton} \rotatebox{90}{Debugging} \rotatebox{90}{Documentation Tooltips}
Atom [X] [X] [X] [X] [X] [X] [X] [X]
Emacs [X] [X] [X] [X] [X] [X] [X] [X]
Sublime [X] [X] [X] [X] [X] [X] [X]
Vim/Neovim [X] [X] [X] [X] [X] [X] [X] [X]
VS Code [X] [X] [X] [X] [X] [X] [X] [X] [X]
BBedit [X] [X] [X] [X] [X]
Geany [X]
gedit [X] [X] [X]
Kakoune [X] [X] [X] [X] [X] [X] [X] [X]
Kate [X] [X] [X] [X] [X] [X]
Micro [X] [X] [X] [X]
Midnight Commander [X]
Textadept [X] [X] [X] [X] [X] [X]
Eclipse [X] [X] [X] [X] [X] [X] [X] [X]
IntelliJ-based IDEs [X] [X] [X] [X] [X] [X] [X] [X] [X]
Visual Studio [X] [X] [X] [X]
GNOME Builder [X] [X] [X] [X] [X] [X]
Ride [X]

Common Crates

  • crates.io/lib.rs
  • Awesome Rust
  • clap (command line argument parser)
  • env_logger, log
  • dotenv
  • serde
  • lazy_static, once_cell (globality, singleton, lazy initialization)
  • nom
  • tokio

Databases

  • sqlx
  • diesel

WebDev

Are we web yet

  • Actix
  • Hyper
  • Rocket
  • reqwest

Footnotes