惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Blog — PlanetScale
Blog — PlanetScale
Y
Y Combinator Blog
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
L
LangChain Blog
S
SegmentFault 最新的问题
J
Java Code Geeks
V
Visual Studio Blog
H
Help Net Security
Stack Overflow Blog
Stack Overflow Blog
aimingoo的专栏
aimingoo的专栏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
Tailwind CSS Blog
Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
H
Hackread – Cybersecurity News, Data Breaches, AI and More
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - Franky
B
Blog RSS Feed
The Cloudflare Blog
MyScale Blog
MyScale Blog
月光博客
月光博客
Microsoft Security Blog
Microsoft Security Blog
美团技术团队

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
[Rust Guide] 13.4. Capturing the Environment With Closures
SomeB1oody · 2026-06-22 · via DEV Community

13.4.0 Before We Begin

During its design, Rust drew inspiration from many languages, and functional programming had a particularly strong influence on Rust. Functional programming often includes passing functions as values to parameters, returning them from other functions, assigning them to variables for later execution, and so on.

In this chapter, we will discuss some Rust features that are similar to what many languages call functional features:

  • Closures (this article)
  • Iterators
  • Improving the I/O Project with Closures and Iterators
  • Performance of Closures and Iterators

If you find this helpful, please like, bookmark, and follow. To keep learning along, follow this series.

13.4.1 Closures Can Capture Their Environment

Closures have a capability that functions do not: a closure can access variables in the scope where it is defined.

Take a look at an example:

fn main() {
    let x = 4;
    let equal_to_x = |z| z == x;
    let y = 4;
    assert!(equal_to_x(y));
}

The closure part is:

let equal_to_x = |z| z == x;

Some people may find it hard to distinguish the roles of = and == here, so let’s rewrite it another way:

let equal_to_x = |z| {
    z == x;
}

In other words, the closure takes z as its parameter, compares it with x (which is 4, because x = 4 was defined above), and returns a boolean. If they are equal, the result is true; otherwise it is false.

Here the closure directly accesses the variable x in the same scope, which functions cannot do.

But this feature has a cost: it introduces memory overhead. In most cases we do not need a closure to capture its environment, and we do not want the extra overhead either. That is why functions are not allowed to capture variables from the environment, and defining and using a function never introduces this kind of overhead.

13.4.2 How Closures Capture Values From Their Environment

Closures capture values from the environment in three ways, just like functions receive parameters in three ways:

  • Taking ownership, whose trait is FnOnce because a closure cannot take and consume the same variable more than once, so it can only be called once.
  • Mutable borrowing, whose trait is FnMut
  • Immutable borrowing, whose trait is Fn

When a programmer creates a closure, Rust infers which trait should be used based on how the closure uses values from the environment:

  • All closures implement FnOnce, because every closure can be called at least once
  • Closures that do not move captured variables implement FnMut
  • Closures that do not need mutable access to captured variables implement Fn

In fact, these three have an inclusion relationship: every Fn also implements FnMut, and every FnMut also implements FnOnce.

13.4.3 The move Keyword

Using the move keyword before the parameter list forces a closure to take ownership of the environment values it uses. This is most useful when passing a closure to a new thread and moving data so that it belongs to that new thread.

Take a look at an example:

fn main() {
    let x = vec![1, 2, 3];
    let equal_to_x = move |z| z == x;
    println!("can't use x here {:?}", x);
    let y = vec![1, 2, 3];
    assert!(equal_to_x(y));
}

After using move, ownership of x moves into the closure, so x can no longer be used afterward.

13.4.4 Best Practice

When you specify one of the Fn trait bounds, start with Fn. Depending on what happens inside the closure, the compiler will tell you if FnOnce or FnMut is needed instead.