fn take_ownership(s: String) {
println!("Took ownership: {}", s);
} // s is dropped here
fn main() {
let message = String::from("hello");
take_ownership(message);
// println!("{}", message); // ❌ compile error: value moved
}
Rust's ownership system guarantees memory safety without garbage collection. Each value has exactly one owner, and when ownership is transferred (moved), the previous owner can't use it anymore. This prevents double-frees and use-after-free bugs at compile time. The pattern below shows a String being moved into a function; after the call, the original binding is invalid. The compiler enforces this. For expensive operations like building large data structures, I design APIs to take ownership when the caller won't need the value again, avoiding unnecessary clones. This zero-cost abstraction is the foundation of Rust's safety guarantees, and once you internalize it, you stop fighting the borrow checker and start designing better APIs.
Related snips
struct Config<'a> {
name: &'a str,
value: &'a str,
}
fn parse_config(line: &str) -> Config {
Lifetime annotations for flexible borrowing in structs
use crossbeam::channel::unbounded;
use std::thread;
fn main() {
let (tx, rx) = unbounded();
Crossbeam for advanced concurrent data structures
use tracing::{info, instrument};
#[instrument]
fn process_request(user_id: u64) {
info!(user_id, "Processing request");
// Work happens here
tracing for structured logging and distributed tracing
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
Channels (mpsc) for message passing between threads
use clap::Parser;
#[derive(Parser, Debug)]
#[command(author, version, about)]
struct Args {
#[arg(short, long)]
clap for CLI argument parsing with derive macros
macro_rules! create_function {
($func_name:ident) => {
fn $func_name() {
println!("Called {}", stringify!($func_name));
}
};
Declarative macros (macro_rules!) for code generation
Share this code
Here's the card — post it anywhere.