### Install and Initialize Rustlings Source: https://github.com/rust-lang/rustlings/blob/main/website/content/_index.md Use Cargo to install Rustlings, initialize it in your project directory, and then start the exercises. ```bash cargo install rustlings ``` ```bash rustlings init ``` ```bash cd rustlings ``` ```bash rustlings ``` -------------------------------- ### Exercise Configuration Example (info.toml) Source: https://context7.com/rust-lang/rustlings/llms.txt Configure exercise metadata, including welcome/final messages, hints, and test/Clippy settings, within the `info.toml` file. This example shows settings for multiple exercises. ```toml # Example info.toml for community exercises format_version = 1 # Optional welcome message shown at start welcome_message = """Welcome to Rust Basics! These exercises will teach you the fundamentals.""" # Optional message shown after completing all exercises final_message = """Congratulations! You've completed all exercises! Continue learning at https://doc.rust-lang.org/book/""" # Define each exercise [[exercises]] name = "hello" dir = "00_intro" # Optional subdirectory hint = """ Try using the println! macro. Example: println!(\"Hello, world!\"); """ [[exercises]] name = "variables1" dir = "01_variables" # test = true # Default: run cargo test (set false to skip tests) # strict_clippy = false # Default: allow warnings (set true to deny) hint = """ Variables must be initialized before use. Add a value: let x = 5; """ [[exercises]] name = "quiz1" dir = "quizzes" skip_check_unsolved = true # Skip check that exercise starts unsolved hint = "This quiz tests your knowledge of variables and functions." ``` -------------------------------- ### Initialize Rustlings Directory Source: https://github.com/rust-lang/rustlings/blob/main/website/content/setup/index.md Run this command after installing Rustlings to set up the project directory. This prepares the environment for the exercises. ```bash rustlings init ``` -------------------------------- ### Get Cargo Version Source: https://github.com/rust-lang/rustlings/blob/main/CONTRIBUTING.md Run this command to get the version of Cargo installed on your system. This is required when reporting a bug. ```bash cargo --version ``` -------------------------------- ### Install GCC on Fedora Source: https://github.com/rust-lang/rustlings/blob/main/website/content/setup/index.md On Fedora Linux systems, install the GCC compiler, which is required as a linker for Rust. ```bash sudo dnf install gcc ``` -------------------------------- ### Install Xcode Command Line Tools on MacOS Source: https://github.com/rust-lang/rustlings/blob/main/website/content/setup/index.md On MacOS, install Xcode and its developer tools using this command. This provides necessary build tools for Rust. ```bash xcode-select --install ``` -------------------------------- ### Get Rustlings Version Source: https://github.com/rust-lang/rustlings/blob/main/CONTRIBUTING.md Run this command to get the version of Rustlings installed. This is required when reporting a bug. ```bash rustlings --version ``` -------------------------------- ### Install GCC on Debian Source: https://github.com/rust-lang/rustlings/blob/main/website/content/setup/index.md On Debian-based Linux systems, install the GCC compiler, which is required as a linker for Rust. ```bash sudo apt install gcc ``` -------------------------------- ### Navigate and Launch Rustlings Source: https://github.com/rust-lang/rustlings/blob/main/website/content/setup/index.md After initialization, change into the rustlings directory and launch the tool to begin the exercises. This command starts the interactive learning process. ```bash cd rustlings/ rustlings ``` -------------------------------- ### Initialize Rustlings Exercises Source: https://context7.com/rust-lang/rustlings/llms.txt Initialize a new Rustlings exercise directory with the `init` command. This creates a `rustlings/` directory with all exercise files and configuration. Navigate into the directory and start Rustlings. ```bash rustlings init ``` ```bash cd rustlings/ rustlings ``` -------------------------------- ### Install Rustlings Source: https://context7.com/rust-lang/rustlings/llms.txt Install Rustlings using Cargo, Rust's package manager. Use the --locked flag if installation fails. Verify installation with `rustlings --version`. ```bash cargo install rustlings ``` ```bash cargo install rustlings --locked ``` ```bash rustlings --version ``` -------------------------------- ### Install Rustlings using Cargo Source: https://github.com/rust-lang/rustlings/blob/main/website/content/setup/index.md Use this command to download and compile the Rustlings tool. Ensure you have the latest Rust version installed. ```bash cargo install rustlings ``` -------------------------------- ### Exercise Metadata Example Source: https://github.com/rust-lang/rustlings/blob/main/CONTRIBUTING.md This TOML snippet shows the required metadata for a Rustlings exercise. Include this in `rustlings-macros/info.toml` when adding a new exercise. ```toml [[exercises]] name = "yourTopicN" dir = "yourTopic" hint = """ A useful (multi-line) hint for your exercise. Include links to a section in The Book or a documentation page.""" ``` -------------------------------- ### Retry Rustlings Installation with Locked Flag Source: https://github.com/rust-lang/rustlings/blob/main/website/content/setup/index.md If the initial installation of Rustlings fails, try using the `--locked` flag with the cargo install command. This ensures a consistent build using the lock file. ```bash cargo install rustlings --locked ``` -------------------------------- ### Start Rustlings Watch Mode Source: https://context7.com/rust-lang/rustlings/llms.txt Start the interactive watch mode by running `rustlings` without arguments. This mode monitors the `exercises/` directory for changes and reruns the current exercise. Use flags to customize behavior like manual runs or disabling editor opening. ```bash rustlings ``` ```bash rustlings --manual-run ``` ```bash rustlings --no-editor ``` ```bash rustlings --edit-cmd "code" ``` -------------------------------- ### Get Solution File Path in Rustlings Source: https://context7.com/rust-lang/rustlings/llms.txt Retrieves the file path for the solution of a given exercise. ```rust // Get solution file path let sol_path = exercise.sol_path(); // Returns: "solutions/01_variables/variables1.rs" ``` -------------------------------- ### Reset a Rustlings Exercise Source: https://context7.com/rust-lang/rustlings/llms.txt Use the `reset` command to revert an exercise file to its original state. This is useful for discarding changes or starting over. ```bash rustlings reset variables2 ``` ```bash rustlings reset structs1 ``` -------------------------------- ### Initialize and Use AppState in Rust Source: https://context7.com/rust-lang/rustlings/llms.txt Demonstrates initializing the AppState with exercise data and parsing info files. It shows how to access the current exercise, navigate between exercises, and track progress. ```rust // Internal API - used by Rustlings core use crate::app_state::{AppState, StateFileStatus}; use crate::info_file::InfoFile; // Initialize application state let info_file = InfoFile::parse()?; let (mut app_state, status) = AppState::new( info_file.exercises, info_file.final_message.unwrap_or_default(), editor, // Optional editor integration vs_code_term, // Running in VS Code terminal )?; // Access current exercise let exercise = app_state.current_exercise(); println!("Current: {}", exercise.path); // "exercises/01_variables/variables1.rs" println!("Hint: {}", exercise.hint); // Navigate exercises app_state.set_current_exercise_by_name("variables2")?; app_state.set_current_exercise_ind(5)?; // Track progress let done_count = app_state.n_done(); // Number of completed exercises let pending_count = app_state.n_pending(); // Number of remaining exercises let all_exercises = app_state.exercises(); // Slice of all exercises // Reset exercise to original state app_state.reset_current_exercise()?; // Check all exercises in parallel let mut stdout = io::stdout().lock(); let first_pending = app_state.check_all_exercises(&mut stdout)?; // Mark current exercise as complete and advance match app_state.done_current_exercise::(&mut stdout)? { ExercisesProgress::AllDone => println!("Congratulations!"), ExercisesProgress::NewPending => println!("Next exercise ready"), ExercisesProgress::CurrentPending => println!("Current still pending"), } ``` -------------------------------- ### Create a New Community Exercise Project Source: https://github.com/rust-lang/rustlings/blob/main/website/content/community-exercises/index.md Use this command to generate a new project directory for your community exercises. It sets up the necessary file structure and configuration. ```bash rustlings dev new PROJECT_NAME ``` -------------------------------- ### Run Exercise and Solution Files in Rustlings Source: https://context7.com/rust-lang/rustlings/llms.txt Demonstrates the process of running an exercise file and its corresponding solution file using the CmdRunner. Includes steps for compilation, testing, Clippy checks, and execution. The solution file always uses strict Clippy. ```rust // Run an exercise (compile, test, clippy, execute) let cmd_runner = CmdRunner::build()?; let mut output = Vec::with_capacity(16384); // Run the exercise file let success = exercise.run_exercise(Some(&mut output), &cmd_runner)?; // success: true if compilation, tests, and Clippy all pass // Run the solution file (always uses strict Clippy) let solution_success = exercise.run_solution(Some(&mut output), &cmd_runner)?; ``` -------------------------------- ### Rustlings Exercise Build Process Overview Source: https://context7.com/rust-lang/rustlings/llms.txt Outlines the sequence of commands executed by the `run` method for an exercise: cargo build, cargo test, cargo clippy, and binary execution. ```rust // The run method performs these steps: // 1. cargo build --bin // 2. cargo test --bin (if exercise.test is true) // 3. cargo clippy --bin --profile test // 4. Execute the compiled binary ``` -------------------------------- ### Show Rustlings Exercise Hint Source: https://context7.com/rust-lang/rustlings/llms.txt Display the hint for the current or a specified exercise. Hints are stored in the `info.toml` configuration file and provide guidance without revealing the full solution. ```bash rustlings hint ``` ```bash rustlings hint variables2 ``` ```bash rustlings hint structs1 ``` -------------------------------- ### Create New Community Exercises Project Source: https://context7.com/rust-lang/rustlings/llms.txt Use `rustlings dev new` to scaffold a new project for community exercises. This command sets up the necessary directory structure and configuration files. ```bash rustlings dev new my-rust-exercises ``` ```bash rustlings dev new my-rust-exercises --no-git ``` -------------------------------- ### Basic Rust Exercise File Structure Source: https://context7.com/rust-lang/rustlings/llms.txt Standard Rust source files for exercises often contain intentional errors or TODO comments. Users must resolve these to complete the exercise. ```rust // exercises/01_variables/variables2.rs // Example exercise file structure fn main() { // TODO: Change the line below to fix the compiler error. let x; if x == 10 { println!("x is ten!"); } else { println!("x is not ten!"); } } // Solution: Add initialization // let x = 10; ``` -------------------------------- ### Run Single Rustlings Exercise Source: https://context7.com/rust-lang/rustlings/llms.txt Execute a specific exercise by name using the `run` command. If no name is provided, it runs the next pending exercise. This command compiles, tests, and runs Clippy on the exercise. ```bash rustlings run ``` ```bash rustlings run variables2 ``` ```bash rustlings run structs1 ``` -------------------------------- ### Define Exercise Metadata in info.toml Source: https://github.com/rust-lang/rustlings/blob/main/website/content/community-exercises/index.md This TOML snippet shows how to define metadata for a single exercise within the `info.toml` file. Include the exercise name and a hint. ```toml [[exercises]] name = "intro1" hint = """ To finish this exercise, you need to … These links might help you …""" ``` -------------------------------- ### Rust Exercise with Tests Source: https://context7.com/rust-lang/rustlings/llms.txt Exercises can include test functions to validate user implementations. Completion requires passing all tests and having no Clippy errors. ```rust // exercises/07_structs/structs1.rs // Example exercise with tests struct ColorRegularStruct { // TODO: Add the fields that the test `regular_structs` expects. // What types should the fields have? What are the minimum and maximum values for RGB colors? } struct ColorTupleStruct(/* TODO: Add fields */); #[derive(Debug)] struct UnitStruct; fn main() { // You can optionally experiment here. } #[cfg(test)] mod tests { use super::*; #[test] fn regular_structs() { // TODO: Instantiate a regular struct. // let green = assert_eq!(green.red, 0); assert_eq!(green.green, 255); assert_eq!(green.blue, 0); } #[test] fn tuple_structs() { // TODO: Instantiate a tuple struct. // let green = assert_eq!(green.0, 0); assert_eq!(green.1, 255); assert_eq!(green.2, 0); } #[test] fn unit_structs() { // TODO: Instantiate a unit struct. // let unit_struct = let message = format!("{unit_struct:?}s are fun!"); assert_eq!(message, "UnitStructs are fun!"); } } // Solution: // struct ColorRegularStruct { // red: u8, // green: u8, // blue: u8, // } // struct ColorTupleStruct(u8, u8, u8); // let green = ColorRegularStruct { red: 0, green: 255, blue: 0 }; // let green = ColorTupleStruct(0, 255, 0); // let unit_struct = UnitStruct; ``` -------------------------------- ### Check Exercise Validity Source: https://github.com/rust-lang/rustlings/blob/main/website/content/community-exercises/index.md Use this command to validate your newly created exercises and their solutions. It checks for common issues and ensures everything is set up correctly before publishing. ```bash rustlings dev check ``` -------------------------------- ### Check All Rustlings Exercises Source: https://context7.com/rust-lang/rustlings/llms.txt Verify the status of all exercises simultaneously using parallel execution with the `check-all` command. This updates the exercise state and provides a progress visualization. ```bash rustlings check-all ``` -------------------------------- ### List Directory Contents Source: https://github.com/rust-lang/rustlings/blob/main/CONTRIBUTING.md Run this command to list the contents of the current directory in long format. This may be required when reporting a bug. ```bash ls -la ``` -------------------------------- ### Update `Cargo.toml` for Community Exercises Source: https://context7.com/rust-lang/rustlings/llms.txt Run `rustlings dev update` to regenerate the `[[bin]]` entries in `Cargo.toml` after adding or removing exercises. This ensures all exercise and solution binaries are correctly listed. ```bash # Update Cargo.toml with current exercises rustlings dev update # This updates the bin list in Cargo.toml: # [[bin]] # name = "hello" # path = "exercises/00_intro/hello.rs" # # [[bin]] # name = "hello_sol" # path = "solutions/00_intro/hello.rs" ``` -------------------------------- ### Update Cargo.toml for New Exercises Source: https://github.com/rust-lang/rustlings/blob/main/website/content/community-exercises/index.md Run this command to automatically update the `Cargo.toml` file, ensuring new exercises are recognized by the Rustlings build system. This is typically done after adding new exercises. ```bash rustlings dev update ``` -------------------------------- ### Implement RunnableExercise Trait for Exercise Source: https://context7.com/rust-lang/rustlings/llms.txt Shows how the Exercise struct implements the RunnableExercise trait, providing access to exercise properties like name, directory, and strict Clippy settings. ```rust use crate::exercise::RunnableExercise; use crate::cmd::CmdRunner; // Exercise implements RunnableExercise impl RunnableExercise for Exercise { fn name(&self) -> &str { self.name } fn dir(&self) -> Option<&str> { self.dir } fn strict_clippy(&self) -> bool { self.strict_clippy } fn test(&self) -> bool { self.test } } ``` -------------------------------- ### Rustlings Exercise List Mode Controls Source: https://context7.com/rust-lang/rustlings/llms.txt Navigate and manage exercises interactively by pressing 'l' in watch mode. This provides a full-screen interface for browsing, filtering, and selecting exercises. ```bash # In watch mode, press 'l' to enter list mode # List mode keyboard controls: # j/↓ - Move selection down # k/↑ - Move selection up # g/Home - Jump to first exercise # G/End - Jump to last exercise # d - Filter: show only done exercises (toggle) # p - Filter: show only pending exercises (toggle) # s or / - Search exercises by name # c - Continue at selected exercise (set as current) # r - Reset selected exercise # q - Quit list mode (return to watch mode) # Mouse scrolling is also supported for navigation ``` -------------------------------- ### Validate Community Exercises with `dev check` Source: https://context7.com/rust-lang/rustlings/llms.txt Use `rustlings dev check` to validate community exercises for correctness, including compilation, TODO markers, and solution execution. Optional flags can enforce solution presence. ```bash # Check all exercises for issues rustlings dev check # Check and require that all exercises have solutions rustlings dev check --require-solutions ``` -------------------------------- ### Implement String::from<&str> Trait Source: https://github.com/rust-lang/rustlings/blob/main/exercises/15_traits/README.md Demonstrates how the String data type implements the From<&str> trait, allowing conversion from string slices. ```rust String::from("hello") ``` -------------------------------- ### Exercise Metadata with No Tests Source: https://github.com/rust-lang/rustlings/blob/main/CONTRIBUTING.md If an exercise does not have any tests, add `test = false` to its metadata in `rustlings-macros/info.toml`. ```toml [[exercises]] name = "yourTopicN" dir = "yourTopic" test = false hint = """ A useful (multi-line) hint for your exercise. Include links to a section in The Book or a documentation page.""" ``` -------------------------------- ### String Parsing with FromStr in Rust Source: https://github.com/rust-lang/rustlings/blob/main/exercises/23_conversions/README.md Implement the `FromStr` trait to enable parsing strings into custom types using the `.parse()` method. Handle potential errors with `.unwrap()` or other error handling mechanisms. ```rust let p: Person = "Mark,20".parse().unwrap(); ``` -------------------------------- ### Rustlings Watch Mode Commands Source: https://context7.com/rust-lang/rustlings/llms.txt Interactive commands available within Rustlings watch mode for navigation, hints, and exercise management. ```bash n - Move to next exercise (when current is done) h - Show hint for current exercise l - Open exercise list view c - Check all exercises x - Reset current exercise r - Run current exercise (manual mode only) q - Quit watch mode ``` -------------------------------- ### Type Casting with 'as' in Rust Source: https://github.com/rust-lang/rustlings/blob/main/exercises/23_conversions/README.md Use the 'as' operator for simple type casting between primitive types. Ensure the conversion is valid to avoid unexpected behavior. ```rust println!("{}", 1 as f32 + 1.0); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.