Rust by example
Every article answers a single question with code that compiles. Nothing here has to be read in order — open the article that matches what just broke, read it, and go back to your editor.
Working with text
Section titled “Working with text”- What is the difference between String and &str?
- When to use String::from, to_string, or into?
- How to build a string from parts
- How to append to a String without extra allocations
- How to format strings with println! and format!
- How to print without a trailing newline
- How to print to standard error
- How to split a string
- How to iterate over the characters of a string
- How to slice a string safely
- Why can’t you index into a String?
- How to reverse a string
- How to handle UTF-8 text
- How to convert a Vec of bytes to a String
- How to match and replace text with regex
- How to replace placeholders in a template
- How to trim whitespace and strip characters
- How to check whether a string contains a substring
- How to pad and align text in a table
Working with collections
Section titled “Working with collections”- Which collection should you use?
- How to get an element from a Vec without panicking
- Why can’t I modify a Vec while iterating over it?
- What is the difference between a Vec and a slice?
- How to accept both a Vec and a slice in one function
- How to sort a Vec
- How to sort a Vec of structs by a field
- How to deduplicate a Vec
- How to find an element in a Vec
- How to split a Vec into chunks
- Why can’t I use f64 as a HashMap key?
- How to handle missing keys with the entry API
- What is the difference between HashMap and BTreeMap?
- How to check whether a collection contains a value
- Why is a HashMap’s order different every run?
- How to count word frequency with a HashMap
- How to use a Vec as a queue
- How to get the largest element from a collection
- Why does indexing an array out of bounds panic?
- What is the difference between an array and a Vec?
- How to tell the compiler the type of an empty Vec
- How to store different types in one Vec
- How to use itertools for iterator helpers
Reading and writing files
Section titled “Reading and writing files”- How to read a file into a String
- How to read a file line by line
- How to read a file into bytes
- How to write to a file
- How to append to a file without overwriting it
- How to write a file atomically
- How to copy or move a file
- How to delete a file or a whole directory
- How to check whether a file or directory exists
- How to list the files in a directory
- How to walk a directory tree
- How to create a directory and its parents
- How to get the current working directory
- How to find the path of the current executable
- How to join paths without breaking on Windows
- How to read file metadata
- How to work with temporary files
- How to watch files for changes
- How to read and write a tar.gz archive
- How to resize an image
Building a command-line tool
Section titled “Building a command-line tool”- How to read command-line arguments
- How to pass arguments with cargo run
- How to parse arguments with clap
- How to add subcommands with clap
- How to get a good –help for free
- How to read a line from standard input
- How to read several values from one line of input
- How to read standard input until the end
- How to exit with a status code
- How to colour terminal output
- How to detect whether output is a terminal
- How to add a progress bar to a CLI
- How to let a CLI read a config file
- How to test a CLI end to end
- How to build a binary you can hand to someone
- How to cross-compile for another platform
Working with JSON, TOML and CSV
Section titled “Working with JSON, TOML and CSV”- How to deserialize JSON into a struct
- How to serialize a struct to JSON
- How to rename JSON fields with serde
- How to handle a missing field in JSON
- How to serialize an enum with serde
- How to read a JSON config file
- How to parse a TOML config file
- How to read a CSV file into structs
- How to write a CSV file from structs
- How to read a YAML file
- How to parse a query string
Working with numbers
Section titled “Working with numbers”- How to convert a String to a number
- How to convert a number to a String
- How to parse an integer from user input
- How to stop an integer from overflowing
- How to choose between i32 and usize
- What is the difference between f32 and f64?
- What is the difference between as and From for casting?
- How to generate a random number in a range
- How to round a float to a number of decimals
- How to compare floats without surprises
- How to format a number with thousands separators
- How to divide integers and get the remainder
Working with dates and time
Section titled “Working with dates and time”- How to get the current time
- How to parse and format dates with chrono
- How to measure how long something took
- How to convert between timestamps and dates
- How to work with timezones
Talking to the network
Section titled “Talking to the network”- How to make a GET request
- How to POST JSON to an API
- How to set a timeout on a request
- How to read a response header
- How to handle a non-200 status
- How to retry a failed request
- How to make several requests at once
- How to parse JSON from an API
- How to download a file over HTTP
- How to parse a URL
- How to fix a TLS certificate error
- How to send an email from a Rust program
Processes, environment and signals
Section titled “Processes, environment and signals”- How to read environment variables
- How to set an environment variable for a child process
- How to run an external command and read its output
- How to check whether a command exists
- How to pipe data between processes
- How to run a command with a timeout
- How to handle Ctrl+C gracefully
- How to run a task on a timer
Logging and configuration
Section titled “Logging and configuration”- How to add logging with tracing
- How to set the log level without recompiling
- How to log structured fields
- How to create a global with lazy initialisation
- How to merge config from file, environment and flags
- How to write a config file from a struct
- How to keep secrets out of your logs
Talking to a database
Section titled “Talking to a database”- How to connect to Postgres
- How to run a query and read the rows
- How to manage a schema with migrations
- How to get queries checked at compile time
- How to insert a row and get its id
- How to use a transaction
- How to use SQLite in a Rust program
- How to map rows to structs
- How to avoid SQL injection
- How to test against a real database
If you have not written Rust before
Section titled “If you have not written Rust before”Two chapters will save you the most time: the bits that trip everyone up for the things that are simply different, and ownership for the one rule the borrow checker is built on. After that, everything here is fair game — and whether Rust is worth learning at all is a fair question with a fair answer.
When the compiler complains
Section titled “When the compiler complains”Compiler errors is the largest chapter on the site: one article per E-code, with the real compiler output and what it means for the code you wrote. If the message on your screen is an error code, that is the fastest way in.
Rather build something?
Section titled “Rather build something?”The project tracks are the other half of the site — twelve series that end with a working tool, a service you can deploy, or firmware running on real hardware.