19 KiB
19 KiB
∈cludesvg[height=.25\textheight]{img/rust-logo-blk}≠wline An introduction to Rust
- Rust
- Abstract
- Strengths and Weaknesses1
- Strengths and Weaknesses2
- Problems and security Rust tries to conquer
- Where to start?
- Where to find help and stay up to date
- Language
- Mutability and shadowing
- Type aliases
- Tuple structs
- Structs
- Error related types
- Error handling
- Use functional language features
- Control structures
- Tests
- Documentation
- FFI (Foreign Function Interface)
- Cargo
- Setup
- IDE support
- Common Crates
- Footnotes
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)
- Compiled code about same performance as C / C++, and excellent memory and energy efficiency.
- Can avoid 70% of all safety issues present in C / C++, and most memory issues.
- Strong type system prevents data races, brings 'fearless concurrency' (amongst others).
- Seamless C interop, and dozens of supported platforms (based on LLVM).5
- "Most loved language" for 6 years in a row.
- Modern tooling:
cargo
(builds just work),clippy
(450+ code quality lints),rustup
(easy toolchain management).
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
- Tour of Rust
- The Rust Book (
$ rustup docs --book
) - Rust in Easy English
- Rust by Example (
$ rustup docs --rust-by-example
) - The Rust Standard Library (
$ rustup docs --std
) - The Rustonomicon: The Art of unsafe Rust (
$ rustup docs --nomicon
) - Use '
$ rustup help docs
' to get an overview
Other helpful sites
Where to find help and stay up to date
Boards/Blogs
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)
andSomething::default()
Definition of a struct
struct Something {
id: usize,
item: String,
}
Error related types
- Heavy use of
Option<T>
andResult<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
- Integration tests are put into the
Documentation
- Documentation comments:
///
- Markdown notation
cargo doc
runns rustdoc which generates html docscargo doc --open
runs rustdoc and opens the result in a browser- rustdoc documentation: https://doc.rust-lang.org/beta/rustdoc/index.html
FFI (Foreign Function Interface)
Cargo
Cargo
\Huge Cargo
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
- The Cargo Book (
$ rustup docs --cargo
)
Cargo commands/plugins
What I typically use
audit
: AuditCargo.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
Docs
- The Cargo Book.
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
- Actix
- Hyper
- Rocket
- reqwest
Embedded
Are we embedded yet Awesome Embedded Rust Embedonomicon
- avr
- stm
- msp430
- esp32
Footnotes
5
Work on GCC: rust-gcc and gcc rust backend.