### Install Rust Target for Windows ARM Source: https://speedsheet.io/s/rust?q=command-line-only Installs the target for Windows on ARM architecture. Requires a stable toolchain for the target. This example shows installing the target and then building a release. ```bash rustup target add i686-pc-windows-msvc rustup toolchain install stable-i686-pc-windows-msvc cargo build --release --target i686-pc-windows-msvc ``` -------------------------------- ### Install Rust using rustup on Linux/Mac Source: https://speedsheet.io/s/rust Execute this script to install rustup, the Rust toolchain installer, on Linux and macOS systems. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` -------------------------------- ### Using Setup Function in Test Source: https://speedsheet.io/s/rust?q=tests-only Call the custom `setup()` function within a test to initialize test data. ```rust #[test] fn some_test() { let test_data = setup(); ... } ``` -------------------------------- ### Setup Function for Test Fixtures Source: https://speedsheet.io/s/rust?q=tests-only Implement custom `setup()` functions to prepare test environments, as Rust does not have built-in test fixture management. ```rust fn setup() -> setup_data_type { ... } ``` -------------------------------- ### List Installed Rustup Components Source: https://speedsheet.io/s/rust?q=command-line-only Use this command to see all components currently installed in your Rust toolchain. ```bash rustup component list --installed ``` -------------------------------- ### Install evcxr_repl (Rust REPL) Source: https://speedsheet.io/s/rust_tools Install evcxr_repl, an interactive Read-Eval-Print Loop for Rust, which converts code into a main() function for execution. ```bash rustup component add rust-src ``` ```bash cargo install evcxr_repl ``` -------------------------------- ### Install Rust Target for Web Assembly Source: https://speedsheet.io/s/rust?q=command-line-only Installs the target for Web Assembly. This is an experimental target and may be incomplete. ```bash rustup target add wasm32-unknown-unknown cargo build --release --target wasm32-unknown-unknown ``` -------------------------------- ### Install Rust Target for Raspberry Pi 4 (64-bit) Source: https://speedsheet.io/s/rust?q=command-line-only Installs the target for a 64-bit Raspberry Pi 4. Requires `arm-linux-gnueabihf-binutils` and `brew install arm-linux-gnueabihf-binutils`. This target is for ARMv7-A Linux with hardfloat. ```bash rustup target add armv7-unknown-linux-gnueabihf cargo build --release --target armv7-unknown-linux-gnueabihf ``` -------------------------------- ### Install Rust Analyzer preview component Source: https://speedsheet.io/s/rust_tools Install the preview version of the Rust Analyzer Language Server Protocol (LSP) component for enhanced IDE support. ```bash rustup +nightly component add rust-analyzer-preview ``` -------------------------------- ### Example: Displaying a Point Struct Source: https://speedsheet.io/s/rust?q=display-only+trait This example demonstrates how to implement the Display trait for a custom struct 'Point' to format its x and y coordinates as a string. ```Rust use std::fmt; use std::fmt::Display; use std::fmt::Formatter; struct Point { x: i32, y: i32, } impl Display for Point { fn fmt(&self, formatter: &mut Formatter) -> fmt::Result { write!(formatter, "{}, {}", self.x, self.y) } } fn main() { let point = Point { x: 3, y: 4 }; println!("Point: {}", point); } ``` -------------------------------- ### Install Rust Target for Raspberry Pi (32-bit) Source: https://speedsheet.io/s/rust?q=command-line-only Installs the target for a 32-bit Raspberry Pi. Requires `arm-linux-gnueabihf-binutils` and `brew install arm-linux-gnueabihf-binutils`. This target is for ARMv6 Linux with hardfloat. ```bash rustup target add arm-unknown-linux-gnueabihf cargo build --release --target arm-unknown-linux-gnueabihf ``` -------------------------------- ### Creating Vec from a Start Index with Step Source: https://speedsheet.io/s/rust?q=%3A%3Avec Shows how to create a new Vec starting from a specific index to the end, selecting elements with a step. ```rust let from_with_step: Vec<_> = vec_1[start..].iter().step_by(step).cloned().collect(); ``` -------------------------------- ### Run evcxr_repl Source: https://speedsheet.io/s/rust_tools Start the evcxr_repl interactive session for Rust. ```bash evcxr ``` -------------------------------- ### Install Rust using Homebrew on Mac Source: https://speedsheet.io/s/rust Use this command to install the Rust programming language via Homebrew on macOS. ```bash brew install rust ``` -------------------------------- ### Example Function - Square Source: https://speedsheet.io/s/rust An example function that calculates the square of a given f64 value. ```rust fn square(value: f64) -> f64 { return value } ``` -------------------------------- ### Install Clippy with Pedantic and Nursery lints Source: https://speedsheet.io/s/rust_tools Use this command to install Clippy with strict linting configurations, including pedantic and nursery levels, and to warn about the use of unwrap and expect. ```bash cargo clippy --fix -- -W clippy::pedantic -W clippy::nursery -W clippy::unwrap_used -W clippy::expect_used ``` -------------------------------- ### Install Rust Target for Windows ARM Source: https://speedsheet.io/s/rust Installs the target for compiling Rust code for Windows on ARM architecture. Requires `stable-i686-pc-windows-msvc` toolchain and `cargo build --release --target i686-pc-windows-msvc`. The `brew install` command is an alternative for obtaining the toolchain. ```bash rustup target add i686-pc-windows-msvc ``` ```bash rustup toolchain install stable-i686-pc-windows-msvc ``` ```bash cargo build --release --target i686-pc-windows-msvc ``` ```bash brew install stable-i686-pc-windows-msvc ``` -------------------------------- ### Array Slicing Examples in Rust Source: https://speedsheet.io/s/rust?q=array-only Demonstrates various ways to slice arrays in Rust to access elements or sub-arrays. Note that slicing operations like `[start..]` or `[..end]` create slices, which are then often converted to `Vec` for further use. ```rust let first = array_1[0]; let nth = array_1[n]; let second_last = array_1[array_1.len() - 2]; let last = array_1[array_1.len() - 1]; let all_but_first: Vec<_> = array_1[1..].to_vec(); let all_but_last: Vec<_> = array_1[..array_1.len() - 1].to_vec(); let reversed: Vec<_> = array_1.iter().rev().cloned().collect(); let from: Vec<_> = array_1[start..].to_vec(); let to: Vec<_> = array_1[..end_plus_1].to_vec(); let step_over: Vec<_> = array_1.iter().step_by(step).cloned().collect(); let from_to: Vec<_> = array_1[start..=end].to_vec(); let from_to: Vec<_> = array_1[start..end_plus_1].to_vec(); let from_to_with_step: Vec<_> = array_1[start..=end].iter().step_by(step).cloned().collect(); let from_to_with_step: Vec<_> = array_1[start..end_plus_1].iter().step_by(step).cloned().collect(); let from_with_step: Vec<_> = array_1[start..].iter().step_by(step).cloned().collect(); ``` -------------------------------- ### Install Rust Target for Windows Intel Source: https://speedsheet.io/s/rust Installs the target for compiling Rust code for Windows on Intel x86_64 architecture. Preferred method uses `x86_64-pc-windows-msvc`. Usage requires `stable-x86_64-pc-windows-msvc` toolchain and `cargo build --release --target stable-x86_64-pc-windows-msvc`. The `brew install` command is an alternative for obtaining the toolchain. ```bash rustup target add x86_64-pc-windows-msvc ``` ```bash rustup target add x86_64-pc-windows-gnu ``` ```bash rustup toolchain install stable-x86_64-pc-windows-msvc ``` ```bash cargo build --release --target stable-x86_64-pc-windows-msvc ``` ```bash brew install stable-x86_64-pc-windows-msvc ``` -------------------------------- ### List All Available Rust Targets Source: https://speedsheet.io/s/rust?q=command-line-only Displays a comprehensive list of all targets that can be installed and used with rustup. ```bash rustup target list ``` -------------------------------- ### Install Rust Target for Windows Intel (GNU) Source: https://speedsheet.io/s/rust?q=command-line-only Installs the target for Windows on Intel x86_64 architecture using the GNU toolchain. This is an alternative for non-Windows systems. ```bash rustup target add x86_64-pc-windows-gnu ``` -------------------------------- ### Install Rust Target for MacOS x86 Source: https://speedsheet.io/s/rust?q=command-line-only Installs the target for MacOS on x86 architecture. This command is typically followed by a build command specifying the target. ```bash rustup target add x86_64-apple-darwin cargo build --release --target x86_64-apple-darwin ``` -------------------------------- ### Get Clippy Help Source: https://speedsheet.io/s/rust?q=command-line-only Use this command to display the help message for Clippy, listing all available options and configurations. ```bash cargo clippy -- -h ``` -------------------------------- ### Install Cargo Fuzz Source: https://speedsheet.io/s/rust_tools Install Cargo Fuzz, a tool designed for fuzz testing applications by randomly generating data to discover potential issues. ```bash cargo install cargo-fuzz ``` -------------------------------- ### Rust Identifiers Examples Source: https://speedsheet.io/s/rust Provides examples of valid and invalid identifiers in Rust, following the naming conventions. ```rust _identifier identifier 식별자 item_1 ``` ```rust _ 3_items 🎈 ``` -------------------------------- ### Install Rust Target for Raspberry Pi (32 bit) Source: https://speedsheet.io/s/rust Installs the target for compiling Rust code for a 32-bit Raspberry Pi. Requires `arm-linux-gnueabihf-binutils` and `cargo build --release --target arm-unknown-linux-gnueabihf` to use the installed target. Notes that this is for ARMv6 Linux with hardfloat. ```bash rustup target add arm-unknown-linux-gnueabihf ``` ```bash brew install arm-linux-gnueabihf-binutils ``` ```bash cargo build --release --target arm-unknown-linux-gnueabihf ``` -------------------------------- ### Install Rust Target for Raspberry Pi 4 (64 bit) Source: https://speedsheet.io/s/rust Installs the target for compiling Rust code for a 64-bit Raspberry Pi 4. Requires `arm-linux-gnueabihf-binutils` and `cargo build --release --target armv7-unknown-linux-gnueabihf` to use the installed target. Notes that this is for ARMv7-A Linux with hardfloat. ```bash rustup target add armv7-unknown-linux-gnueabihf ``` ```bash brew install arm-linux-gnueabihf-binutils ``` ```bash cargo build --release --target armv7-unknown-linux-gnueabihf ``` -------------------------------- ### Install Rust Target for Windows Intel (MSVC) Source: https://speedsheet.io/s/rust?q=command-line-only Installs the target for Windows on Intel x86_64 architecture using the MSVC toolchain. This is the preferred method for Windows Intel targets. ```bash rustup target add x86_64-pc-windows-msvc rustup toolchain install stable-x86_64-pc-windows-msvc cargo build --release --target stable-x86_64-pc-windows-msvc ``` -------------------------------- ### Get Rust Compiler Version Source: https://speedsheet.io/s/rust?q=command-line-only Displays the installed version of the Rust compiler. ```rust rustc -V ``` ```rust rustc --version ``` -------------------------------- ### Hello World - Name from Command Line Arguments Source: https://speedsheet.io/s/rust Greets a user by name, taking the name from command-line arguments. Prints usage instructions if no name is provided. Joins multiple arguments into a single name string. ```rust use std::env::args; fn main() { let args: Vec = args().collect(); if args.len() < 2 { println!("Usage: {} NAME", args[0]); return; } let name = &args[1..].join(" ");; println!("Hello, {}!", name); } ``` -------------------------------- ### Install Miri for undefined behavior detection Source: https://speedsheet.io/s/rust_tools Install Miri, Rust's tool for detecting undefined behavior in unsafe code by running it in an interpreter. ```bash rustup +nightly component add miri ``` -------------------------------- ### Get Match Start Position Source: https://speedsheet.io/s/rust_regex?q=match-only Returns the index of the first character of the matched text. ```rust match_1.start() ``` -------------------------------- ### Hello World with Command Line Arguments in Rust Source: https://speedsheet.io/s/rust?q=hello+world This example shows how to access and use command-line arguments provided when running the program. It joins all arguments after the program name into a single string for the greeting and includes a usage message if no arguments are provided. ```rust use std::env::args; fn main() { let args: Vec = args().collect(); if args.len() < 2 { println!("Usage: {} NAME", args[0]); return; } let name = &args[1..].join(" ");; println!("Hello, {}!", name); } ``` -------------------------------- ### Rust Match Expression Example Source: https://speedsheet.io/s/rust?q=control-structure-only A practical example of a match expression returning a string value based on an integer input. It demonstrates handling specific values and a default case. ```rust let value = 200; let returned_value = match value { 200 => { "OK" }, 400 => { "Bad Request" }, 500 => { "Server Error" }, _ => { "Unknown" } }; println!("Returns {}.", returned_value); ``` -------------------------------- ### Variable Scope Example Source: https://speedsheet.io/s/rust?q=variables-only Demonstrates global, local, and block scopes, as well as shadowing of variables. ```rust static global_variable:i32 = 1; fn func1() { let local_variable = 2; { let block_variable = 3; } } ``` ```rust fn func1() { let variable_1 = 1; { // Block, Shadows Outer Variable: let variable_1 = 2; } } ``` ```rust let a = 1; println!("local a = {}", a); { let a = 2; println!("block a = {}", a); } println!("local a = {}", a); ``` -------------------------------- ### Documentation Comment Source: https://speedsheet.io/s/rust?q=symbols-only Triple slashes `///` start a documentation comment that generates documentation for the following item. ```rust /// ``` -------------------------------- ### Basic CLAP CLI Argument Parsing Source: https://speedsheet.io/s/rust_tools An example of setting up a command-line interface using the CLAP crate, including version, author, and arguments. ```rust fn clap_main() { let _matches = clap_app!( myapp => (version: "1.0") (author: "Alice A. ") (about: "Does awesome things") (@arg CONFIG: -c --config +takes_value "config") (@arg debug: -d ... "Sets debugging level") (@subcommand test => (about: "controls testing features") (@arg verbose: -v --verbose "Verbose test") ) .get_matches(); // Handle cli args from here } ``` -------------------------------- ### Trie - Get Prefixed Subtree Source: https://speedsheet.io/s/rust_radix_trie Retrieves a subtree containing all entries that start with a given prefix. ```APIDOC ## Trie - Get Prefixed Subtree ### Description Returns all items that start with the partial key. ### Method `get_raw_descendant` ### Parameters - **partial_key** (string) - Required - The prefix to search for. ### Returns `SubTrie` - A SubTrie containing entries that match the prefix. ### Request Example ```rust trie.get_raw_descendant("prefix"); ``` ``` -------------------------------- ### Async SQL Query with Sqlx Source: https://speedsheet.io/s/rust_tools Shows how to establish a connection to a PostgreSQL database and execute a query using the sqlx crate. This example requires a running PostgreSQL instance and the sqlx crate with the 'postgres' feature enabled. ```Rust async fn sqlx() { use sqlx::postgres::PgPool; let pool = PgPool::connect("localhost").await.unwrap(); #[derive(sqlx::FromRow)] struct User { name: String, id: i64, } let _stream = sqlx::query_as::<_, User>( "SELECT * FROM users WHERE email = ? OR name = ?" ) .bind("test@example.com") .bind("test") .fetch_all(&pool); } ``` -------------------------------- ### Get Match Range Source: https://speedsheet.io/s/rust_regex?q=match-only Returns a range representing the start and end indices of the matched text. ```rust match_1.range() ``` -------------------------------- ### Get Substring from Start to Index (ASCII) Source: https://speedsheet.io/s/rust?q=string-only Extracts a substring from the beginning of an ASCII string up to a specified index. ```rust let string_1 = "12345".to_string(); let start_to_index_3 = &string_1[..4]; // "1234" ``` -------------------------------- ### Get Prefixed Subtree from Trie in Rust Source: https://speedsheet.io/s/rust_radix_trie Returns a `SubTrie` containing all items that start with the given partial key. ```rust // Assuming trie_1 is a valid Trie instance // let subtrie = trie_1.get_raw_descendant(partial_key); ``` -------------------------------- ### Get Range of Match Source: https://speedsheet.io/s/rust_regex The `range` method returns a `Range` representing the start and end indices of the matched text within the original string. ```rust = match_1.range() ``` -------------------------------- ### Install Rust Target for MacOS Apple Silicon Source: https://speedsheet.io/s/rust?q=command-line-only Installs the target for MacOS on Apple Silicon (aarch64). This is often used before building a release for this specific architecture. ```bash rustup target add aarch64-apple-darwin cargo build --release --target aarch64-apple-darwin ``` -------------------------------- ### Get Middle Substring with Skip and Take (Unicode) Source: https://speedsheet.io/s/rust?q=string-only Extracts a middle substring using `skip` and `take` with explicit start and end calculations for Unicode strings. ```rust let text = "12345".to_string(); let middle = text.chars().skip(1).take(4 - 1).collect::(); // "234" ``` -------------------------------- ### Install Cargo LLVM Cov for code coverage Source: https://speedsheet.io/s/rust_tools Install the Cargo LLVM Cov tool, which provides unit test code coverage analysis using LLVM. ```bash cargo install cargo-llvm-cov ``` -------------------------------- ### File - Get File Length Source: https://speedsheet.io/s/rust?q=files-only Gets the length of a file in bytes. ```APIDOC ## File - Get File Length ### Description Returns the length of the file in bytes. ### Method `metadata.len()` ### Parameters #### Path Parameters - **metadata** (Metadata) - Required - The metadata object obtained from `std::fs::metadata()`. ### Returns - **u64** - The length of the file in bytes. ### Example ```rust use std::fs::metadata; let metadata = metadata("path/to/your/file")?; let file_length = metadata.len(); ``` ``` -------------------------------- ### Invalid Identifier Examples Source: https://speedsheet.io/s/rust?q=fundamentals-only Shows examples of identifiers that are not allowed in Rust. ```Rust _ 3_items 🎈 ``` -------------------------------- ### Compile and Run Application Source: https://speedsheet.io/s/rust?q=command-line-only Compiles the project if necessary and then runs the main application binary. ```rust cargo run ``` -------------------------------- ### Create Full Directory Path Source: https://speedsheet.io/s/rust?q=files-only Creates a directory and any necessary parent directories if they do not exist. ```rust use std::fs::create_dir_all; create_dir_all("path"); ``` -------------------------------- ### Create a new HashSet Source: https://speedsheet.io/s/rust?q=hashset-only Creates an empty `HashSet`. Use this when you need to start with a fresh set. ```Rust use std::collections::HashSet; let set_1: HashSet = HashSet::new(); ``` -------------------------------- ### Check if String Starts With Substring Source: https://speedsheet.io/s/rust?q=string-only Returns true if the string starts with the specified substring. ```Rust let string_1 = String::from("hello world"); let starts_with_hello = string_1.starts_with("hello"); // true ``` -------------------------------- ### Compile and Run Test Executable Source: https://speedsheet.io/s/rust?q=command-line-only First compiles all tests into a binary using `rustc --test`, then runs the resulting executable. ```bash rustc --test program_name.rs program_name ``` -------------------------------- ### Check if String Starts With Another Source: https://speedsheet.io/s/rust?q=str-only Returns true if the string starts with or equals another string. ```Rust str_1.starts_with(str_2) ``` -------------------------------- ### Implicit Return Value Example Source: https://speedsheet.io/s/rust Demonstrates implicit return where the last expression is the return value. ```rust fn square(x: i32) -> i32 { x * x } fn main() { let value = 4; let square = square(value); println!("{} squared is {}. ", value, square); } ``` -------------------------------- ### Get HashMap Properties Source: https://speedsheet.io/s/rust?q=hashmap Illustrates how to get the current length (number of elements) and check if the HashMap is empty. ```rust let length = map.len()); let is_empty = map.is_empty()); ``` -------------------------------- ### Show Rustup Configuration Source: https://speedsheet.io/s/rust?q=command-line-only Displays the current rustup configuration, including available targets, the default target, and the active toolchains. ```bash rustup show ``` -------------------------------- ### Generate and Open Project Documentation Source: https://speedsheet.io/s/rust?q=command-line-only Generates HTML documentation for the project and automatically opens it in the default web browser. ```rust cargo doc --open ``` -------------------------------- ### Valid Identifier Examples Source: https://speedsheet.io/s/rust?q=fundamentals-only Provides examples of valid identifiers according to Rust's naming rules. ```Rust _identifier identifier 식별자 item_1 ``` -------------------------------- ### Create Directory Source: https://speedsheet.io/s/rust?q=files-only Creates a new, empty directory at the specified path. Ensure the parent directories exist. ```rust use std::fs::create_dir; create_dir("path"); ``` -------------------------------- ### Implementing the Into Trait Source: https://speedsheet.io/s/rust?q=into-only+trait Example of how to implement the Into trait for custom type conversions. Requires type annotations or turbofish. ```rust impl Into for FromType { fn into(self) -> ToType { ... } } ``` -------------------------------- ### Get the length of a Vec Source: https://speedsheet.io/s/rust?q=%3A%3Avec Use `len()` to get the number of elements currently in the vector. This returns a `usize` value. ```Rust let vec_1 = vec!["a", "b", "c"]; println!("Size {}.", vec_1.len()); // Prints: "Size 3." ``` -------------------------------- ### Login and Publish Crate Source: https://speedsheet.io/s/rust?q=command-line-only Logs into a crate registry using an authentication token and publishes a crate. ```bash cargo login repository_authentication_token cargo publish ``` -------------------------------- ### Get the Length of a BTreeMap Source: https://speedsheet.io/s/rust?q=btreemap-only Use `len` to get the number of elements currently stored in the BTreeMap. This is an O(1) operation. ```rust btree_map_1.len() ``` -------------------------------- ### Initialize New Rust Project in Current Directory Source: https://speedsheet.io/s/rust?q=command-line-only Initializes a new Rust project in the current directory, creating necessary files like Cargo.toml and a src/ directory. ```rust cargo init ``` -------------------------------- ### Basic Usage of format! Macro Source: https://speedsheet.io/s/rust?q=format%21-only Demonstrates the simplest usage of the format! macro to create a string literal. ```rust format!("Print this."); ``` -------------------------------- ### Async Redis Client with Tokio Source: https://speedsheet.io/s/rust_tools An example of using the tokio runtime to create an asynchronous Redis client, set a key-value pair, and retrieve it. Ensure tokio and mini-redis crates are added to your Cargo.toml. ```Rust use mini_redis::{client, Result as redis_Result}; #[tokio::main] async fn main() -> redis_Result<()> { println!("in tokio"); let mut client = client::connect("127.0.0.1:6379").await?; client.set("hello", "world".into()).await?; let result = client.get("hello").await?; println!("got value result={:?}", result); Ok(()) } ``` -------------------------------- ### Filesystem Utilities with fs2 Source: https://speedsheet.io/s/rust_tools Demonstrates file locking, allocation, and retrieving allocated file size using the fs2 crate. Requires `use fs2::FileExt;`. ```Rust use fs2::FileExt; use std::fs::File; let file_1 = File::open("foo.txt")?; // File is locked until dropped or unlock() called: file_1.lock_exclusive()?; // Allocate 1KB of space: file_1.allocate(1024)?; // Free space: // Returns allocated bytes file_1.allocated_size()?; ``` -------------------------------- ### Get HashMap Value by Key Source: https://speedsheet.io/s/rust?q=hashmap Use `get(key)` to retrieve an `Option` containing a reference to the value associated with the given key. ```Rust let value = hashmap_1.get(key); ``` -------------------------------- ### Build Publishable Crate Source: https://speedsheet.io/s/rust?q=command-line-only Creates a publishable crate. The output is placed in the target/package directory. ```bash cargo package ``` -------------------------------- ### Get the last item from Vec Source: https://speedsheet.io/s/rust?q=%3A%3Avec Use `last()` to get an `Option<&T>` reference to the last element. Returns `None` if the vector is empty. ```Rust vec_1.last(); ``` -------------------------------- ### Path::new Source: https://speedsheet.io/s/rust Creates a new Path instance from a given string slice. This is the primary way to start working with paths. ```APIDOC ## Path - Create = Path::new(path) ### Description Creates an instance of Path from a string slice. ### Usage ```rust use std::path::Path; let path = Path::new("some/path/string"); ``` ### Returns `std::path::Path` ``` -------------------------------- ### Generate Project Documentation Source: https://speedsheet.io/s/rust?q=command-line-only Generates HTML documentation for the project and its dependencies. ```rust cargo doc ``` -------------------------------- ### Get the first item from Vec Source: https://speedsheet.io/s/rust?q=%3A%3Avec Use `first()` to get an `Option<&T>` reference to the first element. Returns `None` if the vector is empty. ```Rust vec_1.first(); ``` -------------------------------- ### Get Immutable Value from BTreeMap Source: https://speedsheet.io/s/rust?q=btreemap-only Use `get` to retrieve an immutable reference to the value associated with a key. Returns `Option<&Value>`. ```rust btree_map_1.get(key) ``` -------------------------------- ### Get Value from OnceLock Source: https://speedsheet.io/s/rust?q=OnceLock Use `get()` to retrieve an optional reference to the value stored in the OnceLock. Returns `None` if the value has not been initialized. ```rust let value: OnceLock = OnceLock::new(); // Initially, get() returns None assert!(value.get().is_none()); ``` -------------------------------- ### Generate Project Documentation (No Dependencies) Source: https://speedsheet.io/s/rust?q=command-line-only Generates HTML documentation for the project only, excluding dependencies. ```rust cargo doc --no-deps ``` -------------------------------- ### Array Slicing Examples in Rust Source: https://speedsheet.io/s/rust?q=array-only Demonstrates various ways to create slices from an array, including inclusive and exclusive end points, and slicing to the end or from the beginning. ```rust let array_1 = [1, 2, 3, 4, 5]; let first = &array_1[0..=0]; // [1] let last = &array_1[array_1.len() - 1.. array_1.len()]; // [5] let index_1 = &array_1[1..=1]; // [2] let index_1_to_3 = &array_1[1..4]; // [2, 3, 4] let index_1_to_end = &array_1[1..]; // [2, 3, 4, 5] let start_to_index_3 = &array_1[..4]; // [1, 2, 3, 4] ``` -------------------------------- ### Rust Test Function Example Source: https://speedsheet.io/s/rust?q=assert%21-only An example of how to use the assert! macro within a Rust test function. This pattern is common for unit testing. ```rust #[test] fn assert_test() { assert!(expression); } ``` -------------------------------- ### Create HashMap with Initial Values Source: https://speedsheet.io/s/rust Creates a HashMap and populates it with initial key-value pairs using `insert`. ```rust use std::collections::HashMap; let mut hashmap_1 = HashMap::new(); hashmap_1.insert("one", "Value 1"); hashmap_1.insert("two", "Value 2"); let value = &hashmap_1.get(&"one"); println!("{}", value.unwrap()); // Prints: "Value 1" ``` -------------------------------- ### Rust Integer Range with Step Source: https://speedsheet.io/s/rust?q=range-only Shows how to create an integer range that increments by a specified step size using `.step_by()`. ```rust use std::ops::Range; let range_1: Range = (0..=10).step_by(2); ``` -------------------------------- ### Use Root Module File Source: https://speedsheet.io/s/rust Demonstrates how to use a function from a root module defined as a single file. Requires a `use` statement to bring the function into scope. ```rust src/ ├── main.rs │ │ use module_name::do_something; │ │ │ do_something(); │ └── some_module.rs use crate::module_name::do_something; do_something(); ``` -------------------------------- ### Create a Path Instance Source: https://speedsheet.io/s/rust Creates a new `Path` instance from a string slice. This is the fundamental way to represent a file system path. ```rust use std::path::Path; let path = Path::new("path"); ``` -------------------------------- ### Get Duration in Microseconds in Rust Source: https://speedsheet.io/s/rust?q=duration-only Use the .as_micros() method on a Duration object to get its value in microseconds as a u128. This is useful for precise time measurements. ```rust let duration_1 = std::time::Duration::from_secs(1); let microseconds = duration_1.as_micros(); ``` -------------------------------- ### Get an item from Vec by index (Panic) Source: https://speedsheet.io/s/rust?q=%3A%3Avec Use direct indexing `vec_1[index]` to access an item. This is faster than `get()` but will panic if the index is out of bounds. ```Rust vec_1[index]; ``` -------------------------------- ### Hello World with User Input in Rust Source: https://speedsheet.io/s/rust?q=hello+world This snippet demonstrates reading a line of text from standard input and then printing a personalized greeting. It includes basic error handling for the input operation and removes the trailing newline character from the input. ```rust use std::io::stdin; fn main() { let mut name = String::new(); println!("name: "); if let Err(error) = stdin().read_line(&mut name) { eprintln!("Error: {}", error); return; } name.pop(); // Remove the newline character. println!("Hello, {}!", name); } ``` -------------------------------- ### Extract Right Slice from Array in Rust Source: https://speedsheet.io/s/rust?q=array-only Returns a slice containing elements from a specified start index to the end of the array. The start index is inclusive. ```rust let array_1 = [1, 2, 3, 4, 5]; let subarray = &array_1[2..]; println!("{:?}", &subarray); // Prints: [3, 4, 5] ``` -------------------------------- ### Generate Project Documentation (Include Private Items) Source: https://speedsheet.io/s/rust?q=command-line-only Generates HTML documentation including private items. ```rust cargo doc --document-private-items ``` -------------------------------- ### Get OS Information Source: https://speedsheet.io/s/rust_tools Retrieve detailed operating system information using the os_info crate. This includes OS type, version, edition, and architecture. ```rust use os_info::get; fn main() { let info = get(); println!("OS Type: {}", info.os_type()); println!("Version: {}", info.version()); println!("Edition: {:?}", info.edition()); println!("Codename: {:?}", info.codename()); println!("Bitness: {}", info.bitness()); println!("Architecture: {:?}", info.architecture()); println!("Formatted: {}", info); } ``` -------------------------------- ### Get Mutable Iterator with .iter_mut() Source: https://speedsheet.io/s/rust Use `.iter_mut()` to get a mutable iterator over the Result. If Ok, it yields one mutable reference. If Err, it yields no items. ```rust = result_1.iter_mut() ``` -------------------------------- ### HashMap - Basic Operations Source: https://speedsheet.io/s/rust?q=hashmap-only Demonstrates basic HashMap operations: creation, insertion, access, update, iteration, removal, checking for existence, and clearing. Requires `Eq + Hash` traits for keys. ```Rust use std::collections::HashMap; // Create and insert let mut map_1 = HashMap::new(); map_1.insert("a", 1); map_1.insert("b", 2); map_1.insert("c", 3); // Access let value = map_1.get("b"); match value { Some(value) => println!("Value for 'b': {}", value), None => println!("Key 'b' not found"), } // Update map_1.insert("b", 22); // Iterate for (key, value) in &map_1 { println!("{}: {}", key, value); } // Remove map_1.remove("a"); // Exists let exists = map_1.contains_key("c"); // Properties let length = map_1.len(); let is_empty = map_1.is_empty(); // Clear map_1.clear(); ``` -------------------------------- ### Get Current Local Time with Chrono Source: https://speedsheet.io/s/rust_tools Demonstrates how to get the current local date and time using the Chrono crate. Ensure Chrono is added to your Cargo.toml. ```rust use chrono::prelude::{DateTime, Local}; let _local: DateTime = Local::now(); // =~ `2014-11-28T21:45:59.324310806+09:00` ``` -------------------------------- ### Create String with Value Source: https://speedsheet.io/s/rust Creates a string with an initial value. All three ways shown are equivalent. The data lives on the heap. ```Rust "a string".to_string() ``` ```Rust String::from("a string") ``` ```Rust let string_1: String = String::from("a string"); ``` -------------------------------- ### Basic Hello World in Rust Source: https://speedsheet.io/s/rust?q=hello+world The most fundamental 'Hello, World!' program in Rust. It prints a static string to the console. ```rust fn main() { println!("Hello world!"); } ``` -------------------------------- ### Get Duration in Seconds in Rust Source: https://speedsheet.io/s/rust?q=duration-only Use the .as_secs() method on a Duration object to get its value in whole seconds as a u64. This is useful for general time calculations. ```rust let duration_1 = std::time::Duration::from_secs(60); let seconds = duration_1.as_secs(); ``` -------------------------------- ### Slicing Vec from Start to Inclusive End in Rust Source: https://speedsheet.io/s/rust?q=std%3A%3Avec%3A%3Avec Creates a new Vec containing elements within a specified range, including both the start and end indices. ```rust let from_to: Vec<_> = vec_1[start..=end].to_vec(); ``` -------------------------------- ### Create New Rust Application Source: https://speedsheet.io/s/rust?q=command-line-only Creates a new Rust project with a standard directory structure, including source files, Cargo.toml, and Git configuration. ```rust cargo new application_name ``` -------------------------------- ### Generate Project Documentation Source: https://speedsheet.io/s/rust Generates HTML documentation for the project and its dependencies. Use `--no-deps` to show only project docs, or `--document-private-items` to include private items. ```bash cargo doc ``` ```bash cargo doc --no-deps ``` ```bash cargo doc --document-private-items ``` -------------------------------- ### Rust Documentation Comment Source: https://speedsheet.io/s/rust?q=Comments+Multiline Use documentation comments (///) to generate API documentation. Each line starts with '///' and precedes the item being documented. ```rust /// This is a doc comment. /// This doc comment /// adds content to the /// following function. fn documented_function() { ... } ``` -------------------------------- ### Generate Documentation (Alternative) Source: https://speedsheet.io/s/rust?q=command-line-only Converts Rust code doc comments into HTML documentation. This command bypasses dependency checks before generation. ```rust cargo rustdoc ``` -------------------------------- ### Get an item from Vec by index (Option) Source: https://speedsheet.io/s/rust?q=%3A%3Avec Use `get(index)` to safely retrieve an item by its index. It returns `Some(&T)` if the index is valid, and `None` if out of bounds. This is slower than direct indexing. ```Rust vec_1.get(index); ``` -------------------------------- ### Show Crate Dependency Tree Source: https://speedsheet.io/s/rust?q=command-line-only Shows the specified crate and its version number within the project's dependency tree. ```bash cargo tree -i crate_name ``` -------------------------------- ### Create New Rust Library Source: https://speedsheet.io/s/rust?q=command-line-only Creates a new Rust library project with a standard structure, including a lib.rs file. ```rust cargo new --lib library_name ``` -------------------------------- ### Get Mutable Reference from Arc> Source: https://speedsheet.io/s/rust?q=arc%2Bmutex Use `arc_1.get_mut()` to attempt to get a mutable reference to the inner value. This method is only available when the `Arc` is the sole owner of the inner `Mutex`. ```rust let mut arc_1 = Arc::new(Mutex::new(5)); // Assuming arc_1 is the only strong reference to the Mutex let mutable_ref_option = arc_1.get_mut(); ``` -------------------------------- ### Create Path with New Extension Source: https://speedsheet.io/s/rust Returns a new path with the file extension replaced or added. The '.' is automatically prepended if needed. ```rust use std::path::Path; let path_1 = Path::new("some/file.old"); let new_path = path_1.with_extension("new"); // Returns PathBuf for "some/file.new" ``` -------------------------------- ### Get or Initialize Value in OnceLock Source: https://speedsheet.io/s/rust?q=OnceLock Use `get_or_init()` to get the contained value or initialize it using a closure if it's not already set. This method is thread-safe and ensures the closure is called at most once. ```rust use std::cell::OnceLock; let value: OnceLock = OnceLock::new(); let initialized_value = value.get_or_init(|| { println!("Initializing..."); "Hello, OnceLock!".to_string() }); assert_eq!(*initialized_value, "Hello, OnceLock!"); // Subsequent calls will return the existing value without re-initializing let same_value = value.get_or_init(|| { panic!("This should not be called again!"); }); assert_eq!(*same_value, "Hello, OnceLock!"); ``` -------------------------------- ### Append to PathBuf Source: https://speedsheet.io/s/rust Joins a directory and subdirectory using the system file separator. Returns a new PathBuf. This example demonstrates creating a path and appending components to it. ```Rust use std::path::PathBuf; use std::path::MAIN_SEPARATOR_STR; let mut pathbuf_1 = PathBuf::new(); pathbuf_1.push(MAIN_SEPARATOR_STR); pathbuf_1.push("home"); pathbuf_1.push("your_name_here"); println!("{}", pathbuf_1.display()); // Prints: /home/your_name_here ``` -------------------------------- ### Slicing Vec from Start to Exclusive End in Rust Source: https://speedsheet.io/s/rust?q=std%3A%3Avec%3A%3Avec Creates a new Vec containing elements within a specified range, including the start index but excluding the end index. ```rust let from_to: Vec<_> = vec_1[start..end_plus_1].to_vec(); ``` -------------------------------- ### Async HTTP GET Request with Reqwest Source: https://speedsheet.io/s/rust_tools Demonstrates how to perform an asynchronous GET request and parse the JSON response using the reqwest crate. Ensure the reqwest crate is added to your Cargo.toml. ```Rust use std::collections::HashMap; async fn get_ip() -> Result<()> { let resp = reqwest::get("https://httpbin.org/ip") .await? .json::>() .await?; println!("{:#?}", resp); Ok(()) } ``` -------------------------------- ### Call a Closure Source: https://speedsheet.io/s/rust Provides examples of how to invoke a closure, passing any required arguments. Closures can be called using standard function call syntax. ```rust closure_1(params) ``` ```rust (closure_1)(params) ``` -------------------------------- ### Get Array Element by Index (Option) Source: https://speedsheet.io/s/rust?q=array-only Safely retrieve an element from an array using its index with the `get` method. It returns an `Option`, providing `None` if the index is out of bounds. This method is slower than direct indexing. ```rust let array_1 = [1, 2, 3]; second = array_1.get(1); ``` -------------------------------- ### Creating Option Instances Source: https://speedsheet.io/s/rust?q=option-only Demonstrates how to create instances of the Option enum, including a Some variant with a value and a None variant. When creating a None variant, the type must be explicitly defined. ```Rust let item_1 = Some(value_1); let item_2 = None; ``` -------------------------------- ### Get File Length in Rust Source: https://speedsheet.io/s/rust?q=files-only After obtaining file metadata using `std::fs::metadata()`, you can get the file's length in bytes by calling the `len()` method on the `Metadata` object. This returns a `u64` value. ```Rust use std::fs; fn main() -> std::io::Result<()> { let metadata = fs::metadata("path")?; let len = metadata.len(); println!("File length: {} bytes", len); Ok(()) } ``` -------------------------------- ### Install Bacon background code checker Source: https://speedsheet.io/s/rust_tools Install the Bacon tool, a background Rust code checker that integrates with IDEs to display standard Rust errors as you code. It can run various cargo commands like build, test, and docs. ```bash cargo install --locked bacon ``` -------------------------------- ### Import All from Parent Module Source: https://speedsheet.io/s/rust?q=tests-only Use `use super::*;` within a test module to import all items from the parent module. ```rust use super::*; ``` -------------------------------- ### Add Regex Crate to Project Source: https://speedsheet.io/s/rust_regex Install the regex crate using Cargo. This is the first step to using regex functionality in your Rust project. ```bash cargo add regex ``` -------------------------------- ### PathBuf - Parent Source: https://speedsheet.io/s/rust Gets the parent directory of the pathbuf. ```APIDOC ## PathBuf - Parent ### Description Gets the parent directory for the pathbuf. ### Returns Option<&OsStr> ### Example ```rust use std::path::PathBuf; let pathbuf_1 = PathBuf::from("/user/your_name_here/file.txt"); if let Some(parent) = pathbuf_1.parent() { println!("Parent directory: {}", parent.to_string_lossy()); } // Prints: Parent directory: /user/your_name_here ``` ``` -------------------------------- ### Basic write! Macro Usage Source: https://speedsheet.io/s/rust?q=write-only Demonstrates the basic usage of the write! macro to print a string to a writer. The writer must implement the std::io::Write trait. ```rust use std::io::{Write, Result}; fn main() -> Result<()> { let mut buffer = Vec::new(); write!(&mut buffer, "Hello, world!")?; println!("Buffer content: {:?}", buffer); Ok(()) } ``` -------------------------------- ### File - Get Metadata Source: https://speedsheet.io/s/rust?q=files-only Retrieves the metadata for a file. ```APIDOC ## File - Get Metadata ### Description Returns the metadata for a file. ### Method `metadata(path)` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the file. ### Returns - **Result** - A Result containing the file's metadata, or an error if it cannot be retrieved. ### Example ```rust use std::fs::metadata; let file_metadata = metadata("path/to/your/file"); ``` ``` -------------------------------- ### HashMap Get Source: https://speedsheet.io/s/rust Retrieves the value associated with the given key. ```APIDOC ## HashMap - Get ### Description Returns the value for the given key. ### Method `get` ### Endpoint `hashmap_1.get(key)` ### Returns `Option<&Value>` ``` -------------------------------- ### PathBuf - File Extension Source: https://speedsheet.io/s/rust Gets the file extension of the pathbuf. ```APIDOC ## PathBuf - File Extension ### Description Gets the file extension of the pathbuf. Returns `None` if no extension is found. ### Returns Option<&OsStr> ### Example ```rust use std::path::PathBuf; let pathbuf_1 = PathBuf::from("/user/your_name_here/file.txt"); if let Some(extension) = pathbuf_1.extension() { println!("File extension: {:?}", extension); } // Prints: File extension: "txt" ``` ``` -------------------------------- ### Get User Audio Directory with Dirs Source: https://speedsheet.io/s/rust_tools Retrieves the user's audio directory path. The output varies by operating system. ```Rust dirs::audio_dir(); // Lin: Some(/home/alice/Music) // Win: Some(C:\Users\Alice\Music) // Mac: Some(/Users/Alice/Music) ``` -------------------------------- ### Initialize u64 with Literal Source: https://speedsheet.io/s/rust Demonstrates initializing a 64-bit unsigned integer using a literal with a type suffix. ```rust let int_1 = 42_u64; println!("{}", int_1); // Prints: "42" ``` -------------------------------- ### write! Macro with Variables Source: https://speedsheet.io/s/rust?q=write-only Shows how to use the write! macro to include variables in the output. The variables are formatted according to the format specifiers. ```rust use std::io::{Write, Result}; fn main() -> Result<()> { let name = "Alice"; let age = 30; let mut buffer = Vec::new(); write!(&mut buffer, "Name: {}, Age: {}", name, age)?; println!("Buffer content: {:?}", buffer); Ok(()) } ``` -------------------------------- ### PathBuf - File Name Source: https://speedsheet.io/s/rust Gets the file name portion of the pathbuf. ```APIDOC ## PathBuf - File Name ### Description Gets the file name portion of the pathbuf (file name and extension, but no directory). ### Returns Option<&OsStr> ### Example ```rust use std::path::PathBuf; let path_1 = PathBuf::from("/user/your_name_here/file.txt"); if let Some(file_name) = path_1.file_name() { println!("File name: {:?}", file_name); } // Prints: File name: "file.txt" ``` ``` -------------------------------- ### Get String Capacity Source: https://speedsheet.io/s/rust?q=string-only Returns the current capacity of the string in bytes. ```Rust let string_1 = String::from("hello"); let capacity = string_1.capacity(); // usize ``` -------------------------------- ### Import All Public Items Source: https://speedsheet.io/s/rust?q=symbols-only The `:: *` syntax is used in `use` declarations to import all public items from a specific module. ```rust used library::module::* ``` -------------------------------- ### File - Get Created Date Source: https://speedsheet.io/s/rust?q=files-only Retrieves the creation date of a file. ```APIDOC ## File - Get Created Date ### Description Returns the creation system time for a file. ### Method `metadata.created()` ### Parameters #### Path Parameters - **metadata** (Metadata) - Required - The metadata object obtained from `std::fs::metadata()`. ### Returns - **Result** - A Result containing the creation system time, or an error. ### Example ```rust use std::fs::metadata; let metadata = metadata("path/to/your/file")?; let created_time = metadata.created(); ``` ``` -------------------------------- ### Create and Insert into HashMap Source: https://speedsheet.io/s/rust?q=hashmap Demonstrates the basic creation of a mutable HashMap and inserting key-value pairs. ```rust let mut map_1 = HashMap::new(); map_1.insert("a", 1); map_1.insert("b", 2); map_1.insert("c", 3); ``` -------------------------------- ### Get Match Length Source: https://speedsheet.io/s/rust_regex?q=match-only Returns the number of characters in the matched text. ```rust match_1.len() ```