From 46b0c0e1338d70cfa34c938404d73c3106cf5446 Mon Sep 17 00:00:00 2001 From: finga Date: Tue, 28 Sep 2021 15:48:10 +0200 Subject: [PATCH] Add further information and rework some sections --- rust-intro.org | 250 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 216 insertions(+), 34 deletions(-) diff --git a/rust-intro.org b/rust-intro.org index ef3b0e3..a53354e 100644 --- a/rust-intro.org +++ b/rust-intro.org @@ -36,11 +36,10 @@ *** Rust, the language - First appearance 2010 + - Rust is the coating closest to the bare metal - 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++ + - Ownership, lifetimes, traits, functional paradigms, zero-cost + and zero-size abstractions - A well designed language and ecosystem ** Strengths and Weaknesses[fn:strengths] @@ -81,7 +80,7 @@ - Thread safety / concurreny - Segfaults - Error handling - - Zero-cost abstractions + - Zero-cost and zero-size abstractions ** Where to start? *** First Steps @@ -98,21 +97,46 @@ - [[https://cheats.rs][cheats.rs]] - [[https://programming-idioms.org/cheatsheet/Rust][programming-idioms.org]] -** Where to find help and stay up to date +** Where to share, find help and stay up to date +*** Online sharing/testing + - [[https://play.rust-lang.org/][play.rust-lang.org]] + - [[https://godbolt.org/][godbolt.org]] (Not only for Rust, but it is also supported) + *** Chat (Discord) - [[https://discord.gg/rust-lang][The Rust Programming Language]] - [[https://discord.com/invite/tcbkpyQ][The Rust Programming Language Community Server]] -*** Boards/Blogs +*** Boards and Blogs - [[https://blog.rust-lang.org/][Rust Blog]] - [[https://www.reddit.com/r/rust][r/rust]] - [[https://this-week-in-rust.org/][This Week in Rust]] ** Language - - Semicolons have meaning + - Semicolons have meaning (statements vs. expressions) - Mutability - Shadowing - Functional paradigms + - Pattern matching + - Memory safety + - Meaningful compiler warnings and errors + +** Statements vs. expressions +*** Statements + #+BEGIN_SRC rust + let something = true; + fn_call(); + #+END_SRC +*** Expressions + ~false~, ~x + y~, ~fn_call()~ +*** Example + #+BEGIN_SRC rust + let bool_value = true; + let value = if bool_value { + "true".to_string() + } else { + "false".to_string() + }; + #+END_SRC ** Mutability and shadowing *** Immutable variable @@ -133,6 +157,15 @@ #+END_SRC ** Type aliases +*** Type aliases example + #+BEGIN_SRC rust + type Frequency = u64; + let clock: Frequency = 8_000_000 + + #[allow(non_camel_case_types)] + type u64_t = u64; + let another_clock: Frequency = 16_000_000 as u64_t; + #+END_SRC ** Tuple structs *** Definition of a tuple struct @@ -152,7 +185,7 @@ #+END_SRC ** Structs - - Direct access vs. getter and setter + - Direct access vs. getter and setter (~pub~ keyword) - ~Something::new(item)~ and ~Something::default()~ *** Definition of a struct @@ -163,6 +196,53 @@ } #+END_SRC +** Enums +*** Enum example + #+BEGIN_SRC rust + enum Event { + Receive, + Send(String), + Reset { address: u64, hard: bool }, + } + + let new_event = Event::Send("A message".to_owned()); + #+END_SRC + +** ~if let~ + +** Pattern matching and some macros +*** Simple ~match~ + #+BEGIN_SRC rust + match an_enum { + MyEnum::Something => todo!("This has to be done"), + MyEnum::SomethingElse(_) => unimplemented!("This is not implemented"), + MyEnum::AnotherThing(e) => println!("It is another thing: {}", e), + _ => unreachable!(), + }; + #+END_SRC + +*** Assigning ~match~ + #+BEGIN_SRC rust + let maturity = match age { + 0 | 1 => "infant", + 2..=12 => "child", + 13..=19 => "teen", + _ => "...", + }; + #+END_SRC + +** Loops[fn:reference_loops] +*** Loops + - ~loop~: infinite loops + - ~while~: loops until a predicate is false + - ~while let~: loops until a pattern is matched + - ~for~: loop over an iterator until it is empty + +*** Loop labels + - ~break~: terminate/exit a loop + - ~continue~: exit the current iteration and jump to the loop + header + ** Error related types - Heavy use of ~Option~ and ~Result~ @@ -203,17 +283,57 @@ ... #+END_SRC -** Use functional language features +** Printing + When printing something, ~{}~ uses the ~std::fmt::Display~ trait + and ~{:?}~ uses the ~std::fmt::Debug~ trait. + +*** ~print!()~ and ~println!()~ + #+BEGIN_SRC rust + let amount = 3; + let fields = vec![0,2,5]; + + println!("We have {} of {:?}", amount, fields); + #+END_SRC + Prints: ~We have 3 of [0, 2, 5]~ + +** Deriving ~Debug~ + To enable printing of structs or enums when their fields implement + ~Debug~ they can be derived with following annotation. + +*** Deriving ~Debug~ + #+BEGIN_SRC rust + #[derive(Debug)] + struct Something { + id: usize, + item: String, + } + #+END_SRC + +** Implementing ~Display~ +*** Implementing ~Display~ + #+BEGIN_SRC rust + use std::fmt; + + struct Something { + id: usize, + item: String, + } + + impl fmt::Display for Something { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}: {}", self.id, self.item) + } + } + #+END_SRC + + +** Use more 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 @@ -223,15 +343,21 @@ - Documentation testing - Integration testing - Integration tests are put into the ~src/tests/~ directory + - [[https://doc.rust-lang.org/book/ch11-00-testing.html][Rust Book: Writing Automated Tests]] + - Alastair Reid: [[https://alastairreid.github.io/rust-testability/][Rust Design-for-Testability: a survey]] ** Documentation - Documentation comments: ~///~ - Markdown notation - ~cargo doc~ runns rustdoc which generates html docs - ~cargo doc --open~ runs rustdoc and opens the result in a browser - - rustdoc documentation: https://doc.rust-lang.org/beta/rustdoc/index.html + - [[https://doc.rust-lang.org/rustdoc][rustdoc documentation]] ** FFI (Foreign Function Interface) + - [[https://doc.rust-lang.org/nomicon/ffi.html][Rustonomicon: FFI]] + - [[https://docs.rs/jni/][jni]]: Java bindings for Rust + - [[https://bheisler.github.io/post/calling-rust-in-python/][Calling Rust From Python]] + - [[https://github.com/rusterlium/rustler][Rustler]]: Write Erlang NIFs in Rust * Cargo ** Cargo @@ -242,10 +368,10 @@ #+ATTR_LaTeX: :height 0.4\textwidth [[./img/cargo.png]] -** What is it? +** What is it and how does it work? - Package manager + - Build chain/tool - Cargo calls ~rustc~, the Rust compiler - - Build tool - A Cargo project contains at least one crate ** Hello, World @@ -277,6 +403,8 @@ ** Docs - [[https://doc.rust-lang.org/cargo/index.html][The Cargo Book]] (~$ rustup docs --cargo~) + - Guillaume Gomez: [[https://blog.guillaume-gomez.fr/articles/2020-03-12+Guide+on+how+to+write+documentation+for+a+Rust+crate][Guide on how to write documentation for a Rust + crate]] ** Cargo commands/plugins *** What I typically use @@ -288,7 +416,8 @@ - ~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. + - ~install-update~: Keep all your Cargo commands/plugins up to + date. *** @@comment: comment@@ Cargo downloads your Rust package's dependencies, compiles your @@ -303,10 +432,13 @@ *** Unofficial [[https://crates.io][~crates.io~]] frontend [[https://lib.rs][lib.rs]] same but different.. -** Docs - - The [[https://doc.rust-lang.org/cargo/][Cargo Book]]. - * Setup +** Setup + \Huge + #+BEGIN_CENTER + How to get all that stuff? + #+END_CENTER + ** Install the Rust-Toolchain *** Install Rust From [[https://rustup.rs][rustup.rs]]: @@ -345,8 +477,7 @@ $ rustup update #+END_SRC -* IDE support -** Are we IDE yet?[fn:9] +** IDE support aka are we IDE yet?[fn:areweideyet] \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} | |---------------------+--------------------------------------------+----------------------------------------------+--------------------------+---------------------------------+-------------------------+---------------------------------+---------------------------------+---------------------------+----------------------------------------| @@ -371,24 +502,67 @@ | Ride | [X] | | | | | | | | | * Common Crates +** General - [[https://crates.io][crates.io]]/[[https://lib.rs][lib.rs]] - [[https://github.com/rust-unofficial/awesome-rust][Awesome Rust]] - - clap (command line argument parser) - - env_logger, log - dotenv - - serde - - lazy_static, once_cell (globality, singleton, lazy initialization) + - [[https://tokio.rs/][tokio]] + +** Parsing/Encoding + - clap: The command line argument parser (if starting a new project + I would use v3.0.0-beta) + - [[https://serde.rs/][serde]] - nom - - tokio + - [[https://pest.rs/][pest]] + +** Error handling + - anyhow + - thiserror + - snafu + - easy-error + +** Logging + - log: a lightweight logging facade + + - env_logger + - simple_logger + - simplelog + - pretty_env_logger + - stderrlog + - flexi_logger + - log4rs + - fern + - and many many more (checkout the log readme[fn:log_readme]) + +** Testing + - quickcheck + - proptest + +** Data handling + - lazy_static + - once_cell (globality, singleton, lazy initialization) + - [[http://plv.mpi-sws.org/rustbelt/ghostcell/][GhostCell]] ** Databases + - [[https://indradb.github.io/][IndraDB]] + - [[https://diesel.rs/][diesel]]: orm and query builder supporting - sqlx - - diesel + - refinery + - barrel + +** Gui ([[https://www.areweguiyet.com/][areweguiyet.com]]) + A small selection of crates I used/tried so far: + - SixtyFPS + - egui + - imgui + - GTK + - relm + - and many many more + - bevy_ui ** WebDev [[https://www.arewewebyet.org/][Are we web yet]] - - Actix - Hyper - Rocket @@ -399,10 +573,16 @@ [[https://niclashoyer.github.io/areweembeddedyet/][Awesome Embedded Rust]] [[https://docs.rust-embedded.org/embedonomicon/][Embedonomicon]] - - avr - - stm - - msp430 - - esp32 + # - Microchip (Atmel) avr + # - stm + # - msp430 + # - esp32 + # - arm + +** Unikernel + https://unikernel.org + + - [[https://github.com/hermitcore/rusty-hermit][RustyHermit]] * Footnotes [fn:rust_fungus] [[https://commons.wikimedia.org/wiki/File:Bruine_roest_op_tarwe_(Puccinia_recondita_f.sp._tritici_on_Triticum_aestivum).jpg][Wikimedia]] @@ -413,4 +593,6 @@ [fn:compiler_speed] [[https://news.ycombinator.com/item?id=23538220][The Rust compiler isn't slow; we are]] [fn:specification] [[https://people.mpi-sws.org/%7Ejung/thesis.html][Understanding and Evolving the Rust Programming Language]] [fn:xkcd_dangling_pointer] [[https://xkcd.com/371/][xkcd.com/371]] +[fn:reference_loops] [[https://doc.rust-lang.org/reference/expressions/loop-expr.html][Rust Reference: Loops]] [fn:areweideyet] [[https://areweideyet.com/][areweideyet.com]] +[fn:log_readme] https://github.com/rust-lang/log#in-executables