### Install probe-rs from source Source: https://rust-classes.com/chapter_embedded If cargo-binstall is not available, you can install probe-rs by building from source using cargo. ```bash $ cargo install probe-rs-tools --locked ``` -------------------------------- ### Install probe-rs from source Source: https://rust-classes.com/print Install the `probe-rs` tool from source using `cargo install` if `cargo-binstall` is not available. It is recommended to use the `--locked` flag for a stable build. ```bash cargo install probe-rs-tools --locked ``` -------------------------------- ### Install probe-rs with cargo-binstall Source: https://rust-classes.com/chapter_embedded Use this command to install the probe-rs tools if you have cargo-binstall already set up. ```bash $ cargo binstall probe-rs-tools ``` -------------------------------- ### Go Goroutine Example Source: https://rust-classes.com/chapter_migration_from_go A basic example of launching a goroutine in Go to execute a function concurrently. ```go package main import ( "fmt" "time" ) func main() { go func() { fmt.Println("Hello from goroutine") }() time.Sleep(1 * time.Second) } ``` -------------------------------- ### Install Rustfmt Source: https://rust-classes.com/chapter_1_1 Installs the Rustfmt code formatting tool. This ensures consistent code style across projects. ```bash cargo install rustfmt ``` -------------------------------- ### Benchmark Output Example (First Run) Source: https://rust-classes.com/print Example output from the first run of `cargo bench`, showing the measured time for the benchmark and identifying outliers. ```text capitalize strings time: [223.59 ns 225.70 ns 228.04 ns] Found 1 outliers among 100 measurements (1.00%) 1 (1.00%) high severe ``` -------------------------------- ### Main Application Entry Point Source: https://rust-classes.com/chapter_7_3 Sets up and starts the Axum web server with a default greeting handler. Requires the 'tokio' runtime. ```rust use crate::{ handler::WebHandler, web::AxumWebServer, }; mod handler; mod model; mod web; #[tokio::main] async fn main() { let handler = WebHandler::default(); let web_server = AxumWebServer::new(handler); web_server.start().await; } ``` -------------------------------- ### Benchmark Output Example (Second Run) Source: https://rust-classes.com/print Example output from a subsequent run of `cargo bench`, comparing performance against the previous run and indicating improvements. ```text capitalize strings time: [219.78 ns 222.41 ns 226.20 ns] change: [-4.7158% -3.0100% -1.3074%] (p = 0.00 < 0.05) Performance has improved. Found 6 outliers among 100 measurements (6.00%) 4 (4.00%) high mild 2 (2.00%) high severe ``` -------------------------------- ### Add Go Dependency with go get Source: https://rust-classes.com/chapter_migration_from_go Demonstrates adding an external package dependency to a Go project using the 'go get' command. ```go go get -u github.com/gorilla/mux ``` -------------------------------- ### Main Application Entry Point Source: https://rust-classes.com/print Sets up and starts the Axum web server with a default handler. This is the main entry point for the application. ```rust __ use crate:: handler::WebHandler, web::AxumWebServer, }; mod handler; mod model; mod web; #[tokio::main] async fn main() { let handler = WebHandler::default(); let web_server = AxumWebServer::new(handler); web_server.start().await; } ``` -------------------------------- ### Basic Axum Server with GET Route Source: https://rust-classes.com/chapter_7_1 Create a simple Axum web server with a single GET route that extracts a path parameter and returns a string. ```rust use axum::{extract::Path, Router, routing::get, serve}; use tokio::net::TcpListener; #[tokio::main] async fn main() { // set up our application with "hello world" route at "/ let app = Router::new().route("/hello/:visitor", get(greet_visitor)); // start the server on port 3000 let listener = TcpListener::bind("0.0.0.0:3000").await.unwrap(); serve(listener, app).await.unwrap(); } /// Extract the `visitor` path parameter and use it to greet the visitor. async fn greet_visitor(Path(visitor): Path) -> String { format!("Hello, {visitor}!") } ``` -------------------------------- ### Rust Tokio Async Task Example Source: https://rust-classes.com/chapter_migration_from_go An equivalent example in Rust using the Tokio runtime to spawn an asynchronous task. ```rust use std::time::Duration; use tokio::task; use tokio::time::sleep; #[tokio::main] async fn main() { task::spawn(async { println!("Hello from tokio"); sleep(Duration::from_secs(1)).await; }).await.unwrap(); } ``` -------------------------------- ### C/C++ Module Organization Example Source: https://rust-classes.com/chapter_migration_from_c Illustrates the traditional C/C++ approach to code organization using header and source files. ```c // math.h int add(int a, int b); // math.c #include "math.h" int add(int a, int b) { return a + b; } // main.c #include #include "math.h" int main() { int result = add(1, 2); printf("%d\n", result); } ``` -------------------------------- ### Import fmt Package in Go Source: https://rust-classes.com/chapter_migration_from_go Example of importing the standard 'fmt' package in Go for formatted I/O operations. ```go import "fmt" ``` -------------------------------- ### Go Channel Communication Example Source: https://rust-classes.com/chapter_migration_from_go Illustrates inter-goroutine communication using channels in Go. ```go package main import ( "fmt" ) func main() { ch := make(chan string) go func() { ch <- "Hello from goroutine" }() msg := <-ch fmt.Println(msg) } ``` -------------------------------- ### Hello, world! Program Source: https://rust-classes.com/chapter_1_1 A basic 'Hello, world!' program in Rust. This is the standard starting point for learning a new programming language. ```rust fn main() { println!("Hello, world!"); } ``` -------------------------------- ### Rust Example with Tokio Tracing and #[instrument] Source: https://rust-classes.com/chapter_7_5 This example demonstrates structured logging using the `tracing` crate. It initializes the tracing subscriber and uses the `#[instrument]` attribute on a function to automatically log function calls, arguments, and return values, along with custom log messages. ```rust use std::thread; use tracing::{debug, info, instrument, warn}; fn main() { tracing_subscriber::fmt::init(); thread::scope(|s| { for i in 0..10 { s.spawn(move || fake_database_operation(i)); } }); } #[instrument] fn fake_database_operation(account_number: i32) { let start_time = std::time::Instant::now(); info!("Reading account record from database"); // randomly sleep up to 0.5 seconds let sleep_duration = std::time::Duration::from_millis((rand::random::() * 500.0) as u64); thread::sleep(sleep_duration); let elapsed_time = start_time.elapsed().as_millis(); if sleep_duration.as_millis() > 400 { warn!("Timeout reading account record from database; operation took {elapsed_time} ms"); return; } else { info!("Successfully read account record from database; operation took {elapsed_time} ms"); } info!("Updating account record in database"); // fail 50% of the time if rand::random::() > 0.5 { warn!("Failed to update account record in database; record locked"); } else { info!("Successfully updated account record in database"); } let elapsed_time = start_time.elapsed().as_millis(); debug!("fake_database_operation completed successfully in {elapsed_time} ms") } ``` -------------------------------- ### Project File Structure Source: https://rust-classes.com/chapter_embedded_stmf401 Illustrates the expected directory and file structure for the STM32F401CC project after setup. This includes configuration files and the main source code. ```tree . ├── Cargo.toml ├── .cargo │ └── config.toml ├── build.rs └── src └── main.rs ``` -------------------------------- ### Example Output from Tokio Tracing Source: https://rust-classes.com/chapter_7_5 This is an example of the structured log output generated by the `tracing` crate. It includes timestamps, log levels, function names, arguments, and custom messages, facilitating detailed application monitoring. ```text 2024-03-29T11:16:47.819412Z INFO fake_database_operation{account_number=6}: logging_example: Reading account record from database 2024-03-29T11:16:47.819422Z INFO fake_database_operation{account_number=1}: logging_example: Reading account record from database 2024-03-29T11:16:47.819446Z INFO fake_database_operation{account_number=3}: logging_example: Reading account record from database 2024-03-29T11:16:47.819453Z INFO fake_database_operation{account_number=4}: logging_example: Reading account record from database 2024-03-29T11:16:47.819443Z INFO fake_database_operation{account_number=7}: logging_example: Reading account record from database 2024-03-29T11:16:47.819489Z INFO fake_database_operation{account_number=8}: logging_example: Reading account record from database 2024-03-29T11:16:47.819468Z INFO fake_database_operation{account_number=5}: logging_example: Reading account record from database 2024-03-29T11:16:47.819410Z INFO fake_database_operation{account_number=2}: logging_example: Reading account record from database 2024-03-29T11:16:47.819407Z INFO fake_database_operation{account_number=0}: logging_example: Reading account record from database 2024-03-29T11:16:47.819518Z INFO fake_database_operation{account_number=9}: logging_example: Reading account record from database 2024-03-29T11:16:47.896003Z INFO fake_database_operation{account_number=9}: logging_example: Successfully read account record from database; operation took 76 ms 2024-03-29T11:16:47.896042Z INFO fake_database_operation{account_number=9}: logging_example: Updating account record in database 2024-03-29T11:16:47.896052Z INFO fake_database_operation{account_number=9}: logging_example: Successfully updated account record in database 2024-03-29T11:16:47.915817Z INFO fake_database_operation{account_number=5}: logging_example: Successfully read account record from database; operation took 96 ms 2024-03-29T11:16:47.915848Z INFO fake_database_operation{account_number=5}: logging_example: Updating account record in database 2024-03-29T11:16:47.915856Z INFO fake_database_operation{account_number=5}: logging_example: Successfully updated account record in database 2024-03-29T11:16:47.925931Z INFO fake_database_operation{account_number=0}: logging_example: Successfully read account record from database; operation took 106 ms 2024-03-29T11:16:47.925981Z INFO fake_database_operation{account_number=0}: logging_example: Updating account record in database 2024-03-29T11:16:47.925992Z INFO fake_database_operation{account_number=0}: logging_example: Successfully updated account record in database ``` -------------------------------- ### Install Clippy Source: https://rust-classes.com/chapter_1_1 Installs the Clippy lint tool using rustup. This tool helps identify common mistakes and stylistic issues in Rust code. ```bash rustup component add clippy ``` -------------------------------- ### Go Range Iteration Example Source: https://rust-classes.com/chapter_migration_from_go Shows how to iterate over a slice using the 'range' keyword in Go, accessing both index and value. ```go package main import "fmt" func main() { numbers := []int{1, 2, 3, 4, 5} for i, number := range numbers { fmt.Println(i, number) } } ``` -------------------------------- ### Example Output of Multi-threaded Rust Logging Source: https://rust-classes.com/chapter_7_5 This is a sample output from the Rust logging example, showing concurrent log messages from multiple threads. Observe the interleaving of INFO and WARN messages, which can become noisy without proper context. ```text [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Successfully read account record from database [2024-03-29T11:07:11Z INFO logging_example] Updating account record in database [2024-03-29T11:07:11Z INFO logging_example] Successfully updated account record in database [2024-03-29T11:07:11Z INFO logging_example] Successfully read account record from database [2024-03-29T11:07:11Z INFO logging_example] Updating account record in database [2024-03-29T11:07:11Z INFO logging_example] Successfully updated account record in database [2024-03-29T11:07:11Z INFO logging_example] Successfully read account record from database [2024-03-29T11:07:11Z INFO logging_example] Updating account record in database [2024-03-29T11:07:11Z WARN logging_example] Failed to update account record in database; record locked [2024-03-29T11:07:12Z INFO logging_example] Successfully read account record from database [2024-03-29T11:07:12Z INFO logging_example] Updating account record in database [2024-03-29T11:07:12Z INFO logging_example] Successfully updated account record in database [2024-03-29T11:07:12Z INFO logging_example] Successfully read account record from database [2024-03-29T11:07:12Z INFO logging_example] Updating account record in database [2024-03-29T11:07:12Z WARN logging_example] Failed to update account record in database; record locked [2024-03-29T11:07:12Z WARN logging_example] Timeout reading account record from database [2024-03-29T11:07:12Z WARN logging_example] Timeout reading account record from database [2024-03-29T11:07:12Z WARN logging_example] Timeout reading account record from database ``` -------------------------------- ### Example Log Output Source: https://rust-classes.com/print This is a sample output from the concurrent Rust logging example. It shows the interleaved log messages from multiple threads, including informational messages for successful operations and warnings for timeouts or failures. ```log [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Reading account record from database [2024-03-29T11:07:11Z INFO logging_example] Successfully read account record from database [2024-03-29T11:07:11Z INFO logging_example] Updating account record in database [2024-03-29T11:07:11Z INFO logging_example] Successfully updated account record in database [2024-03-29T11:07:11Z INFO logging_example] Successfully read account record from database [2024-03-29T11:07:11Z INFO logging_example] Updating account record in database [2024-03-29T11:07:11Z INFO logging_example] Successfully updated account record in database [2024-03-29T11:07:11Z INFO logging_example] Successfully read account record from database [2024-03-29T11:07:11Z INFO logging_example] Updating account record in database [2024-03-29T11:07:11Z WARN logging_example] Failed to update account record in database; record locked [2024-03-29T11:07:12Z INFO logging_example] Successfully read account record from database [2024-03-29T11:07:12Z INFO logging_example] Updating account record in database [2024-03-29T11:07:12Z INFO logging_example] Successfully updated account record in database [2024-03-29T11:07:12Z INFO logging_example] Successfully read account record from database [2024-03-29T11:07:12Z INFO logging_example] Updating account record in database [2024-03-29T11:07:12Z WARN logging_example] Failed to update account record in database; record locked [2024-03-29T11:07:12Z WARN logging_example] Timeout reading account record from database [2024-03-29T11:07:12Z WARN logging_example] Timeout reading account record from database [2024-03-29T11:07:12Z WARN logging_example] Timeout reading account record from database [2024-03-29T11:07:12Z WARN logging_example] Timeout reading account record from database ``` -------------------------------- ### Import Crate from Local Path Source: https://rust-classes.com/print Dependencies can also be added from a local file path. This example adds the `smgr_model` crate from a relative path. ```toml [dependencies] smgr_model = { path = "../smgr_model" } ``` -------------------------------- ### Test Axum Server with Curl Source: https://rust-classes.com/chapter_7_2 Demonstrates how to send a GET request to the /hello/:visitor endpoint of the Axum server using curl. ```bash $ curl http://127.0.0.1:3000/hello/world ``` -------------------------------- ### Specify Crate Version with Features Source: https://rust-classes.com/print When adding a dependency, you can specify the version and enable specific features. This example adds `serde` version 1.0.106 with the `derive` feature. ```toml [dependencies] serde = { version = "1.0.106", features = ["derive"] } ``` -------------------------------- ### JSON Response Example Source: https://rust-classes.com/chapter_7_1 Example of a JSON response returned by the Axum server for a GET request. ```json { "greeting": "Hello", "visitor": "world" } ``` -------------------------------- ### Rust Iteration with Enumerate Example Source: https://rust-classes.com/chapter_migration_from_go Demonstrates iterating over an array in Rust using '.iter().enumerate()' to get both index and value. ```rust fn main() { let numbers = [1, 2, 3, 4, 5]; for (i, number) in numbers.iter().enumerate() { println!("{i} {number}"); } } ``` -------------------------------- ### Main Application Setup with Axum Source: https://rust-classes.com/chapter_7_3 Sets up an Axum web server with routes for greeting visitors and saying goodbye, utilizing a shared Handler state. Requires `axum` and `tokio` crates. ```Rust use std::sync::Arc; use axum::{ extract::{Path, State}, Json, Router, routing::{delete, get}, }; use crate::handler::WebHandler; use crate::model::Greeting; mod handler; mod model; #[tokio::main] async fn main() { // Create a shared state for our application. We use an Arc so that we clone the pointer to the state and // not the state itself. let app_state = Arc::new(WebHandler::default()); // set up our application with "hello world" route at "/ let app = Router::new() .route("/hello/:visitor", get(greet_visitor)) .route("/bye", delete(say_goodbye)) .with_state(app_state); // start the server on port 3000 let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app).await.unwrap(); } /// Extract the `visitor` path parameter and use it to greet the visitor. /// We also use the `State` extractor to access the shared `Handler` and call the `greet` method. /// We use `Json` to automatically serialize the `Greeting` struct to JSON. async fn greet_visitor( State(handler): State>, Path(visitor): Path, ) -> Json { Json(handler.greet(visitor)) } /// Say goodbye to the visitor. async fn say_goodbye(State(handler): State>) -> String { handler.say_goodbye() } ``` -------------------------------- ### Create New Rust Project Source: https://rust-classes.com/chapter_embedded_pi Initializes a new Rust project for the Pico and navigates into the project directory. ```bash cargo new hello_pico_world cd hello_pico_world ``` -------------------------------- ### Creating a New Rust Project with Cargo Source: https://rust-classes.com/chapter_migration_from_java Illustrates how to initialize a new Rust project using Cargo, the standard build system and package manager. ```bash cargo new hello_world cd hello_world ``` -------------------------------- ### Project Structure Source: https://rust-classes.com/print This illustrates the expected directory and file structure for the 'hello_stm32_world' project. ```text . ├── Cargo.toml ├── .cargo │ └── config.toml ├── build.rs └── src └── main.rs ``` -------------------------------- ### Example Rust Code Source: https://rust-classes.com/chapter_2_4_deployment A simple Rust program demonstrating a greeting function. This code serves as an example for building and optimizing. ```rust fn greet(name: &str) { println!("Welcome, {name} to the Rust world!"); } fn main() { greet("Rusty"); } ``` -------------------------------- ### Repetitive Code Example Source: https://rust-classes.com/basics_functions This example demonstrates repetitive code that can be refactored using functions. It prints greetings with different names. ```rust fn main() { let mut first_name = "Marcel"; println!("Hello, {first_name}!"); first_name = "Tom"; println!("Hello, {first_name}!"); first_name = "Dick"; println!("Hello, {first_name}!"); first_name = "Harry"; println!("Hello, {first_name}!"); } ``` -------------------------------- ### Axum Server with GET and DELETE Routes Source: https://rust-classes.com/chapter_7_1 Extend the Axum server to handle both GET and DELETE requests by adding multiple routes to the router. ```rust use axum::{ extract::Path, Router, routing::{delete, get}, serve, }; use tokio::net::TcpListener; #[tokio::main] async fn main() { // set up our application with "hello world" route at "/ let app = Router::new() .route("/hello/:visitor", get(greet_visitor)) .route("/bye", delete(say_goodbye)); // start the server on port 3000 let listener = TcpListener::bind("0.0.0.0:3000").await.unwrap(); serve(listener, app).await.unwrap(); } /// Extract the `visitor` path parameter and use it to greet the visitor. async fn greet_visitor(Path(visitor): Path) -> String { format!("Hello, {visitor}!") } /// Say goodbye to the visitor. async fn say_goodbye() -> String { "Goodbye".to_string() } ``` -------------------------------- ### Pico Project Build Output Source: https://rust-classes.com/print Example output after successfully building and flashing the Pico board with a Rust program. Indicates successful programming and initial log messages. ```text Erasing ✔ [00:00:00] [##########################################################################################################################################################] 16.00 KiB/16.00 KiB @ 90.04 KiB/s (eta 0s ) Programming ✔ [00:00:00] [##########################################################################################################################################################] 16.00 KiB/16.00 KiB @ 41.75 KiB/s (eta 0s ) Finished in 0.587s 0.002258 INFO Hello Pico World! └─ @ └─ :0 1.002317 INFO Hello Pico World! └─ @ └─ :0 2.002338 INFO Hello Pico World! └─ @ └─ :0 ``` -------------------------------- ### Create New Rust Project and Navigate Source: https://rust-classes.com/chapter_embedded Initializes a new Rust project using Cargo and changes the directory to the project root. This is the first step in setting up the embedded project. ```bash cargo new hello_stm32_world cd hello_stm32_world ``` -------------------------------- ### Filter and Capitalize Cities Starting with 'B' Source: https://rust-classes.com/chapter_5_1 Applies a filter to select cities starting with 'b' before capitalizing them. This showcases chaining iterator methods for selective processing. ```rust fn main() { let capitalize = |value: &str| value.to_uppercase(); let cities = vec!["rome", "barcelona", "berlin"]; let cities_caps: Vec = cities .into_iter() .filter(|c| c.starts_with("b")) .map(capitalize) .collect(); println!("{cities_caps:?}"); } ``` -------------------------------- ### Compiling and Running Java Code Source: https://rust-classes.com/chapter_migration_from_java Demonstrates the command-line steps to compile and run a Java program using `javac` and `java`. ```bash javac Main.java java Main ``` -------------------------------- ### Embassy 'Hello World' for Raspberry Pi Pico Source: https://rust-classes.com/print A minimal asynchronous 'Hello World' program for the Raspberry Pi Pico using the embassy framework. It initializes the embassy runtime and prints a message to the console every second. ```rust #![no_std] #![no_main] use defmt::* use embassy_executor::Spawner; use embassy_time::Timer; use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] async fn main(_spawner: Spawner) { let _p = embassy_rp::init(Default::default()); loop { info!("Hello Pico World!"); Timer::after_secs(1).await; } } ``` -------------------------------- ### Blinky Example for External LED Source: https://rust-classes.com/chapter_embedded_pi_hello This modified code toggles an external LED connected to GP16 on the Raspberry Pi Pico every second. It's a variation of the onboard LED example, demonstrating how to control different GPIO pins. ```rust #![no_std] #![no_main] use defmt::* use embassy_executor::Spawner; use embassy_rp::gpio; use embassy_time::Timer; use gpio::{Level, Output}; use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] async fn main(_spawner: Spawner) { let p = embassy_rp::init(Default::default()); let mut led = Output::new(p.PIN_16, Level::Low); loop { info!("led on!"); led.set_high(); Timer::after_secs(1).await; info!("led off!"); led.set_low(); Timer::after_secs(1).await; } } ``` -------------------------------- ### Check if Student Can Start Driving Lessons Source: https://rust-classes.com/exercise_driving_school Implements a method to determine if a student is eligible to start driving lessons based on age and required documents. It uses a helper function to check if the student will turn 17 within the next six months. ```rust impl Student { fn is_seventeen_in_six_months(&self) -> bool { // ... implementation ... } fn can_start_driving_lessons(&self) -> bool { // ... implementation ... } } ``` -------------------------------- ### Main Function Using Fully Qualified Paths Source: https://rust-classes.com/chapter_4_3 Demonstrates creating and using types from the 'database_lib' crate using their full, qualified paths within the main function. ```rust mod database; fn main() { let project = crate::database::project::Project { name: "Rust book".to_string(), }; let person = crate::database::person::Person { name: "Marcel".to_string(), project: Some(project), }; println!("{person:?}"); } ``` -------------------------------- ### Rust Example: Unsafe Modification of Global Static Variable Source: https://rust-classes.com/chapter_migration_from_c This Rust code shows the equivalent of the C example using an `unsafe` block to modify a mutable static variable `COUNTER` from a spawned thread. This highlights that while Rust can perform such operations, it requires explicit `unsafe` blocks to indicate potential undefined behavior. ```rust use std::thread; static mut COUNTER: i32 = 0; fn increment_counter() { unsafe { COUNTER += 1; } } fn main() { let handle = thread::spawn(|| increment_counter()); handle.join().expect("thread panicked"); unsafe { println!("COUNTER: {}", COUNTER); } } ``` -------------------------------- ### Creating a Pointer in C Source: https://rust-classes.com/chapter_migration_from_c Illustrates how to declare and use a pointer to an integer variable in C. ```c #include int main() { int x = 10; int *ptr = &x; printf("Value of x: %d\n", *ptr); } ``` -------------------------------- ### Basic Scope Example Source: https://rust-classes.com/chapter_6_3 Illustrates how variables declared within a block are only accessible within that block. ```Rust fn main() { let x = 42; { let y = 24; println!("x: {}, y: {}", x, y); } // y is not available here println!("x: {}", x); } ``` -------------------------------- ### C preprocessor macro for logging Source: https://rust-classes.com/chapter_migration_from_c An example of a simple C preprocessor macro used for logging messages. ```c #include #define LOG(message) printf("%s\n", message) int main() { LOG("Hello, world!"); } ``` -------------------------------- ### C++ Multiple Inheritance Example Source: https://rust-classes.com/chapter_migration_from_cpp Illustrates multiple inheritance in C++ with Animal and LandAnimal base classes. ```cpp #include class Animal { public: virtual void speak() = 0; }; class LandAnimal { public: virtual void walk() = 0; int nrOfLegs() { return 4; } }; class Dog : public Animal, public LandAnimal { public: void speak() override { std::cout << "Woof!" << std::endl; } void walk() override { std::cout << "Walking on land" << std::endl; } }; int main() { Dog dog; dog.speak(); dog.walk(); std::cout << dog.nrOfLegs() << std::endl; } ``` -------------------------------- ### Compiling C Program with Optimizations Source: https://rust-classes.com/chapter_migration_from_c Shows how to compile a C program with optimization flags enabled for production builds. ```bash $ gcc -O2 -o program program.c ``` -------------------------------- ### Compiling Rust Program in Release Mode Source: https://rust-classes.com/chapter_migration_from_c Demonstrates the command to build a Rust project with optimizations for production. ```bash $ cargo build --release ``` -------------------------------- ### Loop Scope Example Source: https://rust-classes.com/chapter_6_3 Shows that variables declared within a loop's scope are not accessible after the loop finishes. ```Rust fn main() { let x = 42; for i in 0..3 { let y = i * 2; println!("x: {}, y: {}", x, y); } // y is not available here println!("x: {}", x); } ``` -------------------------------- ### Main Application with Embassy for STM32 Source: https://rust-classes.com/print The main entry point for the STM32 application, initializing Embassy, setting up a GPIO pin for an LED, and blinking it periodically. Uses async/await for non-blocking operations. ```rust #![no_std] #![no_main] use defmt::* use embassy_executor::Spawner use embassy_stm32::gpio::{Level, Output, Speed} use embassy_time::Timer use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] async fn main(_spawner: Spawner) { let p = embassy_stm32::init(Default::default()); info!("Hello STM32 World!"); let mut led = Output::new(p.PC13, Level::High, Speed::Low); loop { info!("high"); led.set_high(); Timer::after_millis(300).await; info!("low"); led.set_low(); Timer::after_millis(300).await; } } ``` -------------------------------- ### Get Debug Probe Information Source: https://rust-classes.com/print This command provides detailed information about the connected debug probe and the target chip. ```bash $ probe-rs info ``` -------------------------------- ### Rust Program Output Example Source: https://rust-classes.com/print This shows the expected output when running a basic Rust program that declares and prints a variable. ```bash /Users/me/.cargo/bin/cargo run --color=always --package hello_world --bin hello_world Compiling hello_world v0.1.0 (/Projects/hello_world) Finished dev [unoptimized + debuginfo] target(s) in 1.48s Running `target/debug/hello_world` Hello, world! Process finished with exit code 0 ``` -------------------------------- ### Hello, World! Program in Rust Source: https://rust-classes.com/basics The standard entry point for a Rust application. This code prints 'Hello, world!' to the console. ```rust fn main() { println!("Hello, world!"); } ``` -------------------------------- ### C-style for loop for array initialization and printing Source: https://rust-classes.com/chapter_migration_from_c Demonstrates a typical C-style for loop used for initializing an array and then iterating over it to print elements. ```c #include #include int main() { int size = 10; int* arr = (int*)malloc(size * sizeof(int)); if (arr == NULL) { exit(0); } for (int i = 0; i < size; ++i) { arr[i] = i + 1; } for (int i = 0; i < size; ++i) { printf("%d\n", arr[i]); } } ``` -------------------------------- ### Hello, World! in Java Source: https://rust-classes.com/chapter_migration_from_java A standard 'Hello, World!' program in Java. This serves as a baseline for comparison with Rust. ```java public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); } } ``` -------------------------------- ### Define C-style Enum Source: https://rust-classes.com/chapter_4_8 Defines a C-style enumeration with explicit `u8` values. This serves as the base type for conversion examples. ```rust #![allow(unused)] fn main() { #[repr(u8)] enum Color { Red = 0, Green = 1, Blue = 2, } } ``` -------------------------------- ### Spawn and Manage Multiple Parallel Asynchronous Tasks Source: https://rust-classes.com/chapter_6_2 This example shows how to spawn multiple asynchronous tasks concurrently and collect their results. It utilizes `tokio::spawn` within a loop and demonstrates the use of `async move` to capture loop variables. ```rust use std::time::Duration; use tokio::spawn; use tokio::time::sleep; #[tokio::main] async fn main() { let mut tasks = vec![]; for id in 0..5 { let t = spawn(async move { println!("Async task {} started.", id); sleep(Duration::from_millis((5 - id) * 100)).await; println!("Async task {} done.", id); let result = id * id; // silly calculation... (id, result) }); tasks.push(t); } println!("Launched {} tasks...", tasks.len()); for task in tasks { let (id, result) = task.await.expect("task failed"); println!("Task {} completed with result: {}", id, result); } println!("Ready!"); } ``` -------------------------------- ### Optimized Mutable Variable Usage Source: https://rust-classes.com/chapter_2_2_variables An optimized version of the mutable variable example, ensuring the variable is read before being reassigned, satisfying Clippy. ```Rust fn main() { let mut name = "Rusty"; println!("Welcome, {name} to the Rust world!"); name = "Marcel"; println!("Welcome, {name} to the Rust world!"); } ``` -------------------------------- ### Iterating and Borrowing Values Source: https://rust-classes.com/basics_loops This example shows how to iterate over a vector by borrowing its elements. The vector can be used again after the loop because the elements were borrowed, not moved. ```rust fn main() { let list_of_numbers = vec![10, 25, 8, 14, 3, 42]; println!("I can list these numbers:"); for number in &list_of_numbers { print!("{number},") } println!(); println!("Now, I *can* list these numbers again:"); for number in list_of_numbers { print!("{number},") } } ``` -------------------------------- ### Import Crate from Git Repository Source: https://rust-classes.com/print You can add a dependency directly from a Git repository by specifying the `git` URL, a `tag`, and any necessary `features`. This example imports `kp-lib-rs` from a Bitbucket repository. ```toml [dependencies] kp-lib-rs = { git = "https://bitbucket.forge.somewhere.com/scm/someservice/rust_common.git", tag = "v0.0.555", features = ["common", "smgr"] } ``` -------------------------------- ### STM32F401CC Main Application with Embassy Source: https://rust-classes.com/chapter_embedded_stmf401 The main entry point for the STM32F401CC application using Embassy. It initializes the microcontroller peripherals, sets up a GPIO pin for an LED, and enters a loop to blink the LED with 300ms intervals. Requires `defmt` for logging. ```rust #![no_std] #![no_main] use defmt::* use embassy_executor::Spawner use embassy_stm32::gpio::{Level, Output, Speed} use embassy_time::Timer use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] async fn main(_spawner: Spawner) { let p = embassy_stm32::init(Default::default()); info!("Hello STM32 World!"); let mut led = Output::new(p.PC13, Level::High, Speed::Low); loop { info!("high"); led.set_high(); Timer::after_millis(300).await; info!("low"); led.set_low(); Timer::after_millis(300).await; } } ```