|
|
|
|
<!DOCTYPE HTML>
|
|
|
|
|
<html lang="zh-CN" class="light" dir="ltr">
|
|
|
|
|
<head>
|
|
|
|
|
<!-- Book generated using mdBook -->
|
|
|
|
|
<meta charset="UTF-8">
|
|
|
|
|
<title>闭包 Closure - Rust语言圣经(Rust Course)</title>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<!-- Custom HTML head -->
|
|
|
|
|
|
|
|
|
|
<meta name="description" content="">
|
|
|
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
|
|
|
<meta name="theme-color" content="#ffffff">
|
|
|
|
|
|
|
|
|
|
<link rel="icon" href="../../favicon.svg">
|
|
|
|
|
<link rel="shortcut icon" href="../../favicon.png">
|
|
|
|
|
<link rel="stylesheet" href="../../css/variables.css">
|
|
|
|
|
<link rel="stylesheet" href="../../css/general.css">
|
|
|
|
|
<link rel="stylesheet" href="../../css/chrome.css">
|
|
|
|
|
<link rel="stylesheet" href="../../css/print.css" media="print">
|
|
|
|
|
|
|
|
|
|
<!-- Fonts -->
|
|
|
|
|
<link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
|
|
|
|
|
<link rel="stylesheet" href="../../fonts/fonts.css">
|
|
|
|
|
|
|
|
|
|
<!-- Highlight.js Stylesheets -->
|
|
|
|
|
<link rel="stylesheet" href="../../highlight.css">
|
|
|
|
|
<link rel="stylesheet" href="../../tomorrow-night.css">
|
|
|
|
|
<link rel="stylesheet" href="../../ayu-highlight.css">
|
|
|
|
|
|
|
|
|
|
<!-- Custom theme stylesheets -->
|
|
|
|
|
<link rel="stylesheet" href="../../theme/style.css">
|
|
|
|
|
|
|
|
|
|
</head>
|
|
|
|
|
<body class="sidebar-visible no-js">
|
|
|
|
|
<div id="body-container">
|
|
|
|
|
<!-- Provide site root to javascript -->
|
|
|
|
|
<script>
|
|
|
|
|
var path_to_root = "../../";
|
|
|
|
|
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
|
|
|
|
<script>
|
|
|
|
|
try {
|
|
|
|
|
var theme = localStorage.getItem('mdbook-theme');
|
|
|
|
|
var sidebar = localStorage.getItem('mdbook-sidebar');
|
|
|
|
|
|
|
|
|
|
if (theme.startsWith('"') && theme.endsWith('"')) {
|
|
|
|
|
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
|
|
|
|
|
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
|
|
|
|
|
}
|
|
|
|
|
} catch (e) { }
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<!-- Set the theme before any content is loaded, prevents flash -->
|
|
|
|
|
<script>
|
|
|
|
|
var theme;
|
|
|
|
|
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
|
|
|
|
if (theme === null || theme === undefined) { theme = default_theme; }
|
|
|
|
|
var html = document.querySelector('html');
|
|
|
|
|
html.classList.remove('light')
|
|
|
|
|
html.classList.add(theme);
|
|
|
|
|
var body = document.querySelector('body');
|
|
|
|
|
body.classList.remove('no-js')
|
|
|
|
|
body.classList.add('js');
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
|
|
|
|
|
|
|
|
|
|
<!-- Hide / unhide sidebar before it is displayed -->
|
|
|
|
|
<script>
|
|
|
|
|
var body = document.querySelector('body');
|
|
|
|
|
var sidebar = null;
|
|
|
|
|
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
|
|
|
|
|
if (document.body.clientWidth >= 1080) {
|
|
|
|
|
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
|
|
|
|
|
sidebar = sidebar || 'visible';
|
|
|
|
|
} else {
|
|
|
|
|
sidebar = 'hidden';
|
|
|
|
|
}
|
|
|
|
|
sidebar_toggle.checked = sidebar === 'visible';
|
|
|
|
|
body.classList.remove('sidebar-visible');
|
|
|
|
|
body.classList.add("sidebar-" + sidebar);
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
|
|
|
|
|
<div class="sidebar-scrollbox">
|
|
|
|
|
<ol class="chapter"><li class="chapter-item affix "><a href="../../about-book.html">关于本书</a></li><li class="chapter-item affix "><a href="../../into-rust.html">进入 Rust 编程世界</a></li><li class="chapter-item affix "><a href="../../first-try/sth-you-should-not-do.html">避免从入门到放弃</a></li><li class="chapter-item affix "><a href="../../community.html">社区和锈书</a></li><li class="spacer"></li><li class="chapter-item affix "><a href="../../some-thoughts.html">Xobserve: 一切皆可观测</a></li><li class="chapter-item affix "><a href="../../beat-ai.html">BeatAI: 工程师 AI 入门圣经</a></li><li class="chapter-item affix "><li class="part-title">Rust 语言基础学习</li><li class="spacer"></li><li class="chapter-item "><a href="../../first-try/intro.html"><strong aria-hidden="true">1.</strong> 寻找牛刀,以便小试</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../first-try/installation.html"><strong aria-hidden="true">1.1.</strong> 安装 Rust 环境</a></li><li class="chapter-item "><a href="../../first-try/editor.html"><strong aria-hidden="true">1.2.</strong> 墙推 VSCode!</a></li><li class="chapter-item "><a href="../../first-try/cargo.html"><strong aria-hidden="true">1.3.</strong> 认识 Cargo</a></li><li class="chapter-item "><a href="../../first-try/hello-world.html"><strong aria-hidden="true">1.4.</strong> 不仅仅是 Hello world</a></li><li class="chapter-item "><a href="../../first-try/slowly-downloading.html"><strong aria-hidden="true">1.5.</strong> 下载依赖太慢了?</a></li></ol></li><li class="chapter-item "><a href="../../basic/intro.html"><strong aria-hidden="true">2.</strong> Rust 基础入门</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/variable.html"><strong aria-hidden="true">2.1.</strong> 变量绑定与解构</a></li><li class="chapter-item "><a href="../../basic/base-type/index.html"><strong aria-hidden="true">2.2.</strong> 基本类型</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/base-type/numbers.html"><strong aria-hidden="true">2.2.1.</strong> 数值类型</a></li><li class="chapter-item "><a href="../../basic/base-type/char-bool.html"><strong aria-hidden="true">2.2.2.</strong> 字符、布尔、单元类型</a></li><li class="chapter-item "><a href="../../basic/base-type/statement-expression.html"><strong aria-hidden="true">2.2.3.</strong> 语句与表达式</a></li><li class="chapter-item "><a href="../../basic/base-type/function.html"><strong aria-hidden="true">2.2.4.</strong> 函数</a></li></ol></li><li class="chapter-item "><a href="../../basic/ownership/index.html"><strong aria-hidden="true">2.3.</strong> 所有权和借用</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/ownership/ownership.html"><strong aria-hidden="true">2.3.1.</strong> 所有权</a></li><li class="chapter-item "><a href="../../basic/ownership/borrowing.html"><strong aria-hidden="true">2.3.2.</strong> 引用与借用</a></li></ol></li><li class="chapter-item "><a href="../../basic/compound-type/intro.html"><strong aria-hidden="true">2.4.</strong> 复合类型</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/compound-type/string-slice.html"><strong aria-hidden="true">2.4.1.</strong> 字符串与切片</a></li><li class="chapter-item "><a href="../../basic/compound-type/tuple.html"><strong aria-hidden="true">2.4.2.</strong> 元组</a></li><li class="chapter-item "><a href="../../basic/compound-type/struct.html"><strong aria-hidden="true">2.4.3.</strong> 结构体</a></li><li class="chapter-item "><a href="../../basic/compound-type/enum.html"><strong aria-hidden="true">2.4.4.</strong> 枚举</a></li><li class="chapter-item "><a href="../../basic/compound-type/array.html"><strong aria-hidden="true">2.4.5.</strong> 数组</a></l
|
|
|
|
|
</div>
|
|
|
|
|
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
|
|
|
|
|
<div class="sidebar-resize-indicator"></div>
|
|
|
|
|
</div>
|
|
|
|
|
</nav>
|
|
|
|
|
|
|
|
|
|
<!-- Track and set sidebar scroll position -->
|
|
|
|
|
<script>
|
|
|
|
|
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
|
|
|
|
|
sidebarScrollbox.addEventListener('click', function(e) {
|
|
|
|
|
if (e.target.tagName === 'A') {
|
|
|
|
|
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
|
|
|
|
|
}
|
|
|
|
|
}, { passive: true });
|
|
|
|
|
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
|
|
|
|
|
sessionStorage.removeItem('sidebar-scroll');
|
|
|
|
|
if (sidebarScrollTop) {
|
|
|
|
|
// preserve sidebar scroll position when navigating via links within sidebar
|
|
|
|
|
sidebarScrollbox.scrollTop = sidebarScrollTop;
|
|
|
|
|
} else {
|
|
|
|
|
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
|
|
|
|
|
var activeSection = document.querySelector('#sidebar .active');
|
|
|
|
|
if (activeSection) {
|
|
|
|
|
activeSection.scrollIntoView({ block: 'center' });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<div id="page-wrapper" class="page-wrapper">
|
|
|
|
|
|
|
|
|
|
<div class="page">
|
|
|
|
|
<div id="menu-bar-hover-placeholder"></div>
|
|
|
|
|
<div id="menu-bar" class="menu-bar sticky">
|
|
|
|
|
<div class="left-buttons">
|
|
|
|
|
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
|
|
|
|
|
<i class="fa fa-bars"></i>
|
|
|
|
|
</label>
|
|
|
|
|
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
|
|
|
|
|
<i class="fa fa-paint-brush"></i>
|
|
|
|
|
</button>
|
|
|
|
|
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
|
|
|
|
|
</ul>
|
|
|
|
|
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
|
|
|
|
|
<i class="fa fa-search"></i>
|
|
|
|
|
</button>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<h1 class="menu-title">Rust语言圣经(Rust Course)</h1>
|
|
|
|
|
|
|
|
|
|
<div class="right-buttons">
|
|
|
|
|
<a href="../../print.html" title="Print this book" aria-label="Print this book">
|
|
|
|
|
<i id="print-button" class="fa fa-print"></i>
|
|
|
|
|
</a>
|
|
|
|
|
<a href="https://github.com/sunface/rust-course" title="Git repository" aria-label="Git repository">
|
|
|
|
|
<i id="git-repository-button" class="fa fa-github"></i>
|
|
|
|
|
</a>
|
|
|
|
|
<a href="https://github.com/sunface/rust-course/edit/main/src/advance/functional-programing/closure.md" title="Suggest an edit" aria-label="Suggest an edit">
|
|
|
|
|
<i id="git-edit-button" class="fa fa-edit"></i>
|
|
|
|
|
</a>
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<div id="search-wrapper" class="hidden">
|
|
|
|
|
<form id="searchbar-outer" class="searchbar-outer">
|
|
|
|
|
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
|
|
|
|
|
</form>
|
|
|
|
|
<div id="searchresults-outer" class="searchresults-outer hidden">
|
|
|
|
|
<div id="searchresults-header" class="searchresults-header"></div>
|
|
|
|
|
<ul id="searchresults">
|
|
|
|
|
</ul>
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
|
|
|
|
|
<script>
|
|
|
|
|
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
|
|
|
|
|
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
|
|
|
|
|
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
|
|
|
|
|
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
|
|
|
|
|
});
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<div id="content" class="content">
|
|
|
|
|
<!-- Page table of contents -->
|
|
|
|
|
<div class="sidetoc"><nav class="pagetoc"></nav></div>
|
|
|
|
|
<main>
|
|
|
|
|
<h1 id="闭包-closure"><a class="header" href="#闭包-closure">闭包 Closure</a></h1>
|
|
|
|
|
<p>闭包这个词语由来已久,自上世纪 60 年代就由 <code>Scheme</code> 语言引进之后,被广泛用于函数式编程语言中,进入 21 世纪后,各种现代化的编程语言也都不约而同地把闭包作为核心特性纳入到语言设计中来。那么到底何为闭包?</p>
|
|
|
|
|
<p>闭包是<strong>一种匿名函数,它可以赋值给变量也可以作为参数传递给其它函数,不同于函数的是,它允许捕获调用者作用域中的值</strong>,例如:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let x = 1;
|
|
|
|
|
let sum = |y| x + y;
|
|
|
|
|
|
|
|
|
|
assert_eq!(3, sum(2));
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>上面的代码展示了非常简单的闭包 <code>sum</code>,它拥有一个入参 <code>y</code>,同时捕获了作用域中的 <code>x</code> 的值,因此调用 <code>sum(2)</code> 意味着将 2(参数 <code>y</code>)跟 1(<code>x</code>)进行相加,最终返回它们的和:<code>3</code>。</p>
|
|
|
|
|
<p>可以看到 <code>sum</code> 非常符合闭包的定义:可以赋值给变量,允许捕获调用者作用域中的值。</p>
|
|
|
|
|
<h2 id="使用闭包来简化代码"><a class="header" href="#使用闭包来简化代码">使用闭包来简化代码</a></h2>
|
|
|
|
|
<h3 id="传统函数实现"><a class="header" href="#传统函数实现">传统函数实现</a></h3>
|
|
|
|
|
<p>想象一下,我们要进行健身,用代码怎么实现(写代码什么鬼,健身难道不应该去健身房嘛?答曰:健身太累了,还是虚拟健身好,点到为止)?这里是我的想法:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">use std::thread;
|
|
|
|
|
use std::time::Duration;
|
|
|
|
|
|
|
|
|
|
// 开始健身,好累,我得发出声音:muuuu...
|
|
|
|
|
fn muuuuu(intensity: u32) -> u32 {
|
|
|
|
|
println!("muuuu.....");
|
|
|
|
|
thread::sleep(Duration::from_secs(2));
|
|
|
|
|
intensity
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn workout(intensity: u32, random_number: u32) {
|
|
|
|
|
if intensity < 25 {
|
|
|
|
|
println!(
|
|
|
|
|
"今天活力满满,先做 {} 个俯卧撑!",
|
|
|
|
|
muuuuu(intensity)
|
|
|
|
|
);
|
|
|
|
|
println!(
|
|
|
|
|
"旁边有妹子在看,俯卧撑太low,再来 {} 组卧推!",
|
|
|
|
|
muuuuu(intensity)
|
|
|
|
|
);
|
|
|
|
|
} else if random_number == 3 {
|
|
|
|
|
println!("昨天练过度了,今天还是休息下吧!");
|
|
|
|
|
} else {
|
|
|
|
|
println!(
|
|
|
|
|
"昨天练过度了,今天干干有氧,跑步 {} 分钟!",
|
|
|
|
|
muuuuu(intensity)
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
// 强度
|
|
|
|
|
let intensity = 10;
|
|
|
|
|
// 随机值用来决定某个选择
|
|
|
|
|
let random_number = 7;
|
|
|
|
|
|
|
|
|
|
// 开始健身
|
|
|
|
|
workout(intensity, random_number);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>可以看到,在健身时我们根据想要的强度来调整具体的动作,然后调用 <code>muuuuu</code> 函数来开始健身。这个程序本身很简单,没啥好说的,但是假如未来不用 <code>muuuuu</code> 函数了,是不是得把所有 <code>muuuuu</code> 都替换成,比如说 <code>woooo</code> ?如果 <code>muuuuu</code> 出现了几十次,那意味着我们要修改几十处地方。</p>
|
|
|
|
|
<h4 id="函数变量实现"><a class="header" href="#函数变量实现">函数变量实现</a></h4>
|
|
|
|
|
<p>一个可行的办法是,把函数赋值给一个变量,然后通过变量调用:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">use std::thread;
|
|
|
|
|
use std::time::Duration;
|
|
|
|
|
|
|
|
|
|
// 开始健身,好累,我得发出声音:muuuu...
|
|
|
|
|
fn muuuuu(intensity: u32) -> u32 {
|
|
|
|
|
println!("muuuu.....");
|
|
|
|
|
thread::sleep(Duration::from_secs(2));
|
|
|
|
|
intensity
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn workout(intensity: u32, random_number: u32) {
|
|
|
|
|
let action = muuuuu;
|
|
|
|
|
if intensity < 25 {
|
|
|
|
|
println!(
|
|
|
|
|
"今天活力满满, 先做 {} 个俯卧撑!",
|
|
|
|
|
action(intensity)
|
|
|
|
|
);
|
|
|
|
|
println!(
|
|
|
|
|
"旁边有妹子在看,俯卧撑太low, 再来 {} 组卧推!",
|
|
|
|
|
action(intensity)
|
|
|
|
|
);
|
|
|
|
|
} else if random_number == 3 {
|
|
|
|
|
println!("昨天练过度了,今天还是休息下吧!");
|
|
|
|
|
} else {
|
|
|
|
|
println!(
|
|
|
|
|
"昨天练过度了,今天干干有氧, 跑步 {} 分钟!",
|
|
|
|
|
action(intensity)
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
// 强度
|
|
|
|
|
let intensity = 10;
|
|
|
|
|
// 随机值用来决定某个选择
|
|
|
|
|
let random_number = 7;
|
|
|
|
|
|
|
|
|
|
// 开始健身
|
|
|
|
|
workout(intensity, random_number);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>经过上面修改后,所有的调用都通过 <code>action</code> 来完成,若未来声(动)音(作)变了,只要修改为 <code>let action = woooo</code> 即可。</p>
|
|
|
|
|
<p>但是问题又来了,若 <code>intensity</code> 也变了怎么办?例如变成 <code>action(intensity + 1)</code>,那你又得哐哐哐修改几十处调用。</p>
|
|
|
|
|
<p>该怎么办?没太好的办法了,只能祭出大杀器:闭包。</p>
|
|
|
|
|
<h4 id="闭包实现"><a class="header" href="#闭包实现">闭包实现</a></h4>
|
|
|
|
|
<p>上面提到 <code>intensity</code> 要是变化怎么办,简单,使用闭包来捕获它,这是我们的拿手好戏:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">use std::thread;
|
|
|
|
|
use std::time::Duration;
|
|
|
|
|
|
|
|
|
|
fn workout(intensity: u32, random_number: u32) {
|
|
|
|
|
let action = || {
|
|
|
|
|
println!("muuuu.....");
|
|
|
|
|
thread::sleep(Duration::from_secs(2));
|
|
|
|
|
intensity
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if intensity < 25 {
|
|
|
|
|
println!(
|
|
|
|
|
"今天活力满满,先做 {} 个俯卧撑!",
|
|
|
|
|
action()
|
|
|
|
|
);
|
|
|
|
|
println!(
|
|
|
|
|
"旁边有妹子在看,俯卧撑太low,再来 {} 组卧推!",
|
|
|
|
|
action()
|
|
|
|
|
);
|
|
|
|
|
} else if random_number == 3 {
|
|
|
|
|
println!("昨天练过度了,今天还是休息下吧!");
|
|
|
|
|
} else {
|
|
|
|
|
println!(
|
|
|
|
|
"昨天练过度了,今天干干有氧,跑步 {} 分钟!",
|
|
|
|
|
action()
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
// 动作次数
|
|
|
|
|
let intensity = 10;
|
|
|
|
|
// 随机值用来决定某个选择
|
|
|
|
|
let random_number = 7;
|
|
|
|
|
|
|
|
|
|
// 开始健身
|
|
|
|
|
workout(intensity, random_number);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>在上面代码中,无论你要修改什么,只要修改闭包 <code>action</code> 的实现即可,其它地方只负责调用,完美解决了我们的问题!</p>
|
|
|
|
|
<p>Rust 闭包在形式上借鉴了 <code>Smalltalk</code> 和 <code>Ruby</code> 语言,与函数最大的不同就是它的参数是通过 <code>|parm1|</code> 的形式进行声明,如果是多个参数就 <code>|param1, param2,...|</code>, 下面给出闭包的形式定义:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>|param1, param2,...| {
|
|
|
|
|
语句1;
|
|
|
|
|
语句2;
|
|
|
|
|
返回表达式
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>如果只有一个返回表达式的话,定义可以简化为:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>|param1| 返回表达式
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>上例中还有两点值得注意:</p>
|
|
|
|
|
<ul>
|
|
|
|
|
<li><strong>闭包中最后一行表达式返回的值,就是闭包执行后的返回值</strong>,因此 <code>action()</code> 调用返回了 <code>intensity</code> 的值 <code>10</code></li>
|
|
|
|
|
<li><code>let action = ||...</code> 只是把闭包赋值给变量 <code>action</code>,并不是把闭包执行后的结果赋值给 <code>action</code>,因此这里 <code>action</code> 就相当于闭包函数,可以跟函数一样进行调用:<code>action()</code></li>
|
|
|
|
|
</ul>
|
|
|
|
|
<h2 id="闭包的类型推导"><a class="header" href="#闭包的类型推导">闭包的类型推导</a></h2>
|
|
|
|
|
<p>Rust 是静态语言,因此所有的变量都具有类型,但是得益于编译器的强大类型推导能力,在很多时候我们并不需要显式地去声明类型,但是显然函数并不在此列,必须手动为函数的所有参数和返回值指定类型,原因在于函数往往会作为 API 提供给你的用户,因此你的用户必须在使用时知道传入参数的类型和返回值类型。</p>
|
|
|
|
|
<p>与函数相反,闭包并不会作为 API 对外提供,因此它可以享受编译器的类型推导能力,无需标注参数和返回值的类型。</p>
|
|
|
|
|
<p>为了增加代码可读性,有时候我们会显式地给类型进行标注,出于同样的目的,也可以给闭包标注类型:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>let sum = |x: i32, y: i32| -> i32 {
|
|
|
|
|
x + y
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>与之相比,不标注类型的闭包声明会更简洁些:<code>let sum = |x, y| x + y</code>,需要注意的是,针对 <code>sum</code> 闭包,如果你只进行了声明,但是没有使用,编译器会提示你为 <code>x, y</code> 添加类型标注,因为它缺乏必要的上下文:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>let sum = |x, y| x + y;
|
|
|
|
|
let v = sum(1, 2);
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>这里我们使用了 <code>sum</code>,同时把 <code>1</code> 传给了 <code>x</code>,<code>2</code> 传给了 <code>y</code>,因此编译器才可以推导出 <code>x,y</code> 的类型为 <code>i32</code>。</p>
|
|
|
|
|
<p>下面展示了同一个功能的函数和闭包实现形式:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>fn add_one_v1 (x: u32) -> u32 { x + 1 }
|
|
|
|
|
let add_one_v2 = |x: u32| -> u32 { x + 1 };
|
|
|
|
|
let add_one_v3 = |x| { x + 1 };
|
|
|
|
|
let add_one_v4 = |x| x + 1 ;
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>可以看出第一行的函数和后面的闭包其实在形式上是非常接近的,同时三种不同的闭包也展示了三种不同的使用方式:省略参数、返回值类型和花括号对。</p>
|
|
|
|
|
<p>虽然类型推导很好用,但是它不是泛型,<strong>当编译器推导出一种类型后,它就会一直使用该类型</strong>:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>let example_closure = |x| x;
|
|
|
|
|
|
|
|
|
|
let s = example_closure(String::from("hello"));
|
|
|
|
|
let n = example_closure(5);
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>首先,在 <code>s</code> 中,编译器为 <code>x</code> 推导出类型 <code>String</code>,但是紧接着 <code>n</code> 试图用 <code>5</code> 这个整型去调用闭包,跟编译器之前推导的 <code>String</code> 类型不符,因此报错:</p>
|
|
|
|
|
<pre><code class="language-console">error[E0308]: mismatched types
|
|
|
|
|
--> src/main.rs:5:29
|
|
|
|
|
|
|
|
|
|
|
5 | let n = example_closure(5);
|
|
|
|
|
| ^
|
|
|
|
|
| |
|
|
|
|
|
| expected struct `String`, found integer // 期待String类型,却发现一个整数
|
|
|
|
|
| help: try using a conversion method: `5.to_string()`
|
|
|
|
|
</code></pre>
|
|
|
|
|
<h2 id="结构体中的闭包"><a class="header" href="#结构体中的闭包">结构体中的闭包</a></h2>
|
|
|
|
|
<p>假设我们要实现一个简易缓存,功能是获取一个值,然后将其缓存起来,那么可以这样设计:</p>
|
|
|
|
|
<ul>
|
|
|
|
|
<li>一个闭包用于获取值</li>
|
|
|
|
|
<li>一个变量,用于存储该值</li>
|
|
|
|
|
</ul>
|
|
|
|
|
<p>可以使用结构体来代表缓存对象,最终设计如下:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>struct Cacher<T>
|
|
|
|
|
where
|
|
|
|
|
T: Fn(u32) -> u32,
|
|
|
|
|
{
|
|
|
|
|
query: T,
|
|
|
|
|
value: Option<u32>,
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>等等,我都跟着这本教程学完 Rust 基础了,为何还有我不认识的东东?<code>Fn(u32) -> u32</code> 是什么鬼?别急,先回答你第一个问题:骚年,too young too naive,你以为 Rust 的语法特性就基础入门那一些吗?太年轻了!如果是长征,你才刚到赤水河。</p>
|
|
|
|
|
<p>其实,可以看得出这一长串是 <code>T</code> 的特征约束,再结合之前的已知信息:<code>query</code> 是一个闭包,大概可以推测出,<code>Fn(u32) -> u32</code> 是一个特征,用来表示 <code>T</code> 是一个闭包类型?Bingo,恭喜你,答对了!</p>
|
|
|
|
|
<p>那为什么不用具体的类型来标注 <code>query</code> 呢?原因很简单,每一个闭包实例都有独属于自己的类型,即使于两个签名一模一样的闭包,它们的类型也是不同的,因此你无法用一个统一的类型来标注 <code>query</code> 闭包。</p>
|
|
|
|
|
<p>而标准库提供的 <code>Fn</code> 系列特征,再结合特征约束,就能很好的解决了这个问题. <code>T: Fn(u32) -> u32</code> 意味着 <code>query</code> 的类型是 <code>T</code>,该类型必须实现了相应的闭包特征 <code>Fn(u32) -> u32</code>。从特征的角度来看它长得非常反直觉,但是如果从闭包的角度来看又极其符合直觉,不得不佩服 Rust 团队的鬼才设计。。。</p>
|
|
|
|
|
<p>特征 <code>Fn(u32) -> u32</code> 从表面来看,就对闭包形式进行了显而易见的限制:<strong>该闭包拥有一个<code>u32</code>类型的参数,同时返回一个<code>u32</code>类型的值</strong>。</p>
|
|
|
|
|
<blockquote>
|
|
|
|
|
<p>需要注意的是,其实 Fn 特征不仅仅适用于闭包,还适用于函数,因此上面的 <code>query</code> 字段除了使用闭包作为值外,还能使用一个具名的函数来作为它的值</p>
|
|
|
|
|
</blockquote>
|
|
|
|
|
<p>接着,为缓存实现方法:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>impl<T> Cacher<T>
|
|
|
|
|
where
|
|
|
|
|
T: Fn(u32) -> u32,
|
|
|
|
|
{
|
|
|
|
|
fn new(query: T) -> Cacher<T> {
|
|
|
|
|
Cacher {
|
|
|
|
|
query,
|
|
|
|
|
value: None,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 先查询缓存值 `self.value`,若不存在,则调用 `query` 加载
|
|
|
|
|
fn value(&mut self, arg: u32) -> u32 {
|
|
|
|
|
match self.value {
|
|
|
|
|
Some(v) => v,
|
|
|
|
|
None => {
|
|
|
|
|
let v = (self.query)(arg);
|
|
|
|
|
self.value = Some(v);
|
|
|
|
|
v
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>上面的缓存有一个很大的问题:只支持 <code>u32</code> 类型的值,若我们想要缓存 <code>&str</code> 类型,显然就行不通了,因此需要将 <code>u32</code> 替换成泛型 <code>E</code>,该练习就留给读者自己完成,具体代码可以参考<a href="https://practice-zh.course.rs/functional-programing/closure.html#closure-in-structs">这里</a></p>
|
|
|
|
|
<h2 id="捕获作用域中的值"><a class="header" href="#捕获作用域中的值">捕获作用域中的值</a></h2>
|
|
|
|
|
<p>在之前代码中,我们一直在用闭包的匿名函数特性(赋值给变量),然而闭包还拥有一项函数所不具备的特性:捕获作用域中的值。</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let x = 4;
|
|
|
|
|
|
|
|
|
|
let equal_to_x = |z| z == x;
|
|
|
|
|
|
|
|
|
|
let y = 4;
|
|
|
|
|
|
|
|
|
|
assert!(equal_to_x(y));
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>上面代码中,<code>x</code> 并不是闭包 <code>equal_to_x</code> 的参数,但是它依然可以去使用 <code>x</code>,因为 <code>equal_to_x</code> 在 <code>x</code> 的作用域范围内。</p>
|
|
|
|
|
<p>对于函数来说,就算你把函数定义在 <code>main</code> 函数体中,它也不能访问 <code>x</code>:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let x = 4;
|
|
|
|
|
|
|
|
|
|
fn equal_to_x(z: i32) -> bool {
|
|
|
|
|
z == x
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let y = 4;
|
|
|
|
|
|
|
|
|
|
assert!(equal_to_x(y));
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>报错如下:</p>
|
|
|
|
|
<pre><code class="language-console">error[E0434]: can't capture dynamic environment in a fn item // 在函数中无法捕获动态的环境
|
|
|
|
|
--> src/main.rs:5:14
|
|
|
|
|
|
|
|
|
|
|
5 | z == x
|
|
|
|
|
| ^
|
|
|
|
|
|
|
|
|
|
|
= help: use the `|| { ... }` closure form instead // 使用闭包替代
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>如上所示,编译器准确地告诉了我们错误,甚至同时给出了提示:使用闭包来替代函数,这种聪明令我有些无所适从,总感觉会显得我很笨。</p>
|
|
|
|
|
<h3 id="闭包对内存的影响"><a class="header" href="#闭包对内存的影响">闭包对内存的影响</a></h3>
|
|
|
|
|
<p>当闭包从环境中捕获一个值时,会分配内存去存储这些值。对于有些场景来说,这种额外的内存分配会成为一种负担。与之相比,函数就不会去捕获这些环境值,因此定义和使用函数不会拥有这种内存负担。</p>
|
|
|
|
|
<h3 id="三种-fn-特征"><a class="header" href="#三种-fn-特征">三种 Fn 特征</a></h3>
|
|
|
|
|
<p>闭包捕获变量有三种途径,恰好对应函数参数的三种传入方式:转移所有权、可变借用、不可变借用,因此相应的 <code>Fn</code> 特征也有三种:</p>
|
|
|
|
|
<ol>
|
|
|
|
|
<li><code>FnOnce</code>,该类型的闭包会拿走被捕获变量的所有权。<code>Once</code> 顾名思义,说明该闭包只能运行一次:</li>
|
|
|
|
|
</ol>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn fn_once<F>(func: F)
|
|
|
|
|
where
|
|
|
|
|
F: FnOnce(usize) -> bool,
|
|
|
|
|
{
|
|
|
|
|
println!("{}", func(3));
|
|
|
|
|
println!("{}", func(4));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let x = vec![1, 2, 3];
|
|
|
|
|
fn_once(|z|{z == x.len()})
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p><strong>仅</strong>实现 <code>FnOnce</code> 特征的闭包在调用时会转移所有权,所以显然不能对已失去所有权的闭包变量进行二次调用:</p>
|
|
|
|
|
<pre><code class="language-console">error[E0382]: use of moved value: `func`
|
|
|
|
|
--> src\main.rs:6:20
|
|
|
|
|
|
|
|
|
|
|
1 | fn fn_once<F>(func: F)
|
|
|
|
|
| ---- move occurs because `func` has type `F`, which does not implement the `Copy` trait
|
|
|
|
|
// 因为`func`的类型是没有实现`Copy`特性的 `F`,所以发生了所有权的转移
|
|
|
|
|
...
|
|
|
|
|
5 | println!("{}", func(3));
|
|
|
|
|
| ------- `func` moved due to this call // 转移在这
|
|
|
|
|
6 | println!("{}", func(4));
|
|
|
|
|
| ^^^^ value used here after move // 转移后再次用
|
|
|
|
|
|
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>这里面有一个很重要的提示,因为 <code>F</code> 没有实现 <code>Copy</code> 特征,所以会报错,那么我们添加一个约束,试试实现了 <code>Copy</code> 的闭包:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn fn_once<F>(func: F)
|
|
|
|
|
where
|
|
|
|
|
F: FnOnce(usize) -> bool + Copy,// 改动在这里
|
|
|
|
|
{
|
|
|
|
|
println!("{}", func(3));
|
|
|
|
|
println!("{}", func(4));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let x = vec![1, 2, 3];
|
|
|
|
|
fn_once(|z|{z == x.len()})
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>上面代码中,<code>func</code> 的类型 <code>F</code> 实现了 <code>Copy</code> 特征,调用时使用的将是它的拷贝,所以并没有发生所有权的转移。</p>
|
|
|
|
|
<pre><code class="language-console">true
|
|
|
|
|
false
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>如果你想强制闭包取得捕获变量的所有权,可以在参数列表前添加 <code>move</code> 关键字,这种用法通常用于闭包的生命周期大于捕获变量的生命周期时,例如将闭包返回或移入其他线程。</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>use std::thread;
|
|
|
|
|
let v = vec![1, 2, 3];
|
|
|
|
|
let handle = thread::spawn(move || {
|
|
|
|
|
println!("Here's a vector: {:?}", v);
|
|
|
|
|
});
|
|
|
|
|
handle.join().unwrap();
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<ol start="2">
|
|
|
|
|
<li><code>FnMut</code>,它以可变借用的方式捕获了环境中的值,因此可以修改该值:</li>
|
|
|
|
|
</ol>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let mut s = String::new();
|
|
|
|
|
|
|
|
|
|
let update_string = |str| s.push_str(str);
|
|
|
|
|
update_string("hello");
|
|
|
|
|
|
|
|
|
|
println!("{:?}",s);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>在闭包中,我们调用 <code>s.push_str</code> 去改变外部 <code>s</code> 的字符串值,因此这里捕获了它的可变借用,运行下试试:</p>
|
|
|
|
|
<pre><code class="language-console">error[E0596]: cannot borrow `update_string` as mutable, as it is not declared as mutable
|
|
|
|
|
--> src/main.rs:5:5
|
|
|
|
|
|
|
|
|
|
|
4 | let update_string = |str| s.push_str(str);
|
|
|
|
|
| ------------- - calling `update_string` requires mutable binding due to mutable borrow of `s`
|
|
|
|
|
| |
|
|
|
|
|
| help: consider changing this to be mutable: `mut update_string`
|
|
|
|
|
5 | update_string("hello");
|
|
|
|
|
| ^^^^^^^^^^^^^ cannot borrow as mutable
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>虽然报错了,但是编译器给出了非常清晰的提示,想要在闭包内部捕获可变借用,需要把该闭包声明为可变类型,也就是 <code>update_string</code> 要修改为 <code>mut update_string</code>:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let mut s = String::new();
|
|
|
|
|
|
|
|
|
|
let mut update_string = |str| s.push_str(str);
|
|
|
|
|
update_string("hello");
|
|
|
|
|
|
|
|
|
|
println!("{:?}",s);
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>这种写法有点反直觉,相比起来前面的 <code>move</code> 更符合使用和阅读习惯。但是如果你忽略 <code>update_string</code> 的类型,仅仅把它当成一个普通变量,那么这种声明就比较合理了。</p>
|
|
|
|
|
<p>再来看一个复杂点的:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let mut s = String::new();
|
|
|
|
|
|
|
|
|
|
let update_string = |str| s.push_str(str);
|
|
|
|
|
|
|
|
|
|
exec(update_string);
|
|
|
|
|
|
|
|
|
|
println!("{:?}",s);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn exec<'a, F: FnMut(&'a str)>(mut f: F) {
|
|
|
|
|
f("hello")
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>这段代码中<code>update_string</code>没有使用mut关键字修饰,而上文提到想要在闭包内部捕获可变借用,需要用关键词把该闭包声明为可变类型。我们确实这么做了———<code>exec(mut f: F)</code>表明我们的<code>exec</code>接收的是一个可变类型的闭包。这段代码中<code>update_string</code>看似被声明为不可变闭包,但是<code>exec(mut f: F)</code>函数接收的又是可变参数,为什么可以正常执行呢?</p>
|
|
|
|
|
<p>rust不可能接受类型不匹配的形参和实参通过编译,我们提供的实参又是可变的,这说明<code>update_string</code>一定是一个可变类型的闭包,我们不妨看看rust-analyzer自动给出的类型标注:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span> let mut s: String = String::new();
|
|
|
|
|
|
|
|
|
|
let update_string: impl FnMut(&str) = |str| s.push_str(str);
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>rust-analyzer给出的类型标注非常清晰的说明了 <code>update_string</code> 实现了 <code>FnMut</code> 特征。</p>
|
|
|
|
|
<p>为什么<code>update_string</code>没有用<code>mut</code>修饰却是一个可变类型的闭包?事实上,<code>FnMut</code>只是trait的名字,声明变量为<code>FnMut</code>和要不要mut没啥关系,<code>FnMut</code>是推导出的特征类型,<code>mut</code>是rust语言层面的一个修饰符,用于声明一个绑定是可变的。Rust从特征类型系统和语言修饰符两方面保障了我们的程序正确运行。</p>
|
|
|
|
|
<p>我们在使用<code>FnMut</code>类型闭包时需要捕获外界的可变借用,因此我们常常搭配<code>mut</code>修饰符使用。但我们要始终记住,二者是相互独立的。</p>
|
|
|
|
|
<p>因此,让我们再回头分析一下这段代码:在<code>main</code>函数中,首先创建了一个可变的字符串<code>s</code>,然后定义了一个可变类型闭包<code>update_string</code>,该闭包接受一个字符串参数并将其追加到<code>s</code>中。接下来调用了<code>exec</code>函数,并将<code>update_string</code>闭包的所有权移交给它。最后打印出了字符串<code>s</code>的内容。</p>
|
|
|
|
|
<p>细心的读者可能注意到,我们在上文的分析中提到<code>update_string</code>闭包的所有权被移交给了<code>exec</code>函数。这说明<code>update_string</code>没有实现<code>Copy</code>特征,但并不是所有闭包都没有实现<code>Copy</code>特征,闭包自动实现<code>Copy</code>特征的规则是,只要闭包捕获的类型都实现了<code>Copy</code>特征的话,这个闭包就会默认实现<code>Copy</code>特征。</p>
|
|
|
|
|
<p>我们来看一个例子:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>let s = String::new();
|
|
|
|
|
let update_string = || println!("{}",s);
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>这里取得的是<code>s</code>的不可变引用,所以是能<code>Copy</code>的。而如果拿到的是<code>s</code>的所有权或可变引用,都是不能<code>Copy</code>的。我们刚刚的代码就属于第二类,取得的是<code>s</code>的可变引用,没有实现<code>Copy</code>。</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>// 拿所有权
|
|
|
|
|
let s = String::new();
|
|
|
|
|
let update_string = move || println!("{}", s);
|
|
|
|
|
|
|
|
|
|
exec(update_string);
|
|
|
|
|
// exec2(update_string); // 不能再用了
|
|
|
|
|
|
|
|
|
|
// 可变引用
|
|
|
|
|
let mut s = String::new();
|
|
|
|
|
let mut update_string = || s.push_str("hello");
|
|
|
|
|
exec(update_string);
|
|
|
|
|
// exec1(update_string); // 不能再用了
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<ol start="3">
|
|
|
|
|
<li><code>Fn</code> 特征,它以不可变借用的方式捕获环境中的值
|
|
|
|
|
让我们把上面的代码中 <code>exec</code> 的 <code>F</code> 泛型参数类型修改为 <code>Fn(&'a str)</code>:</li>
|
|
|
|
|
</ol>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let mut s = String::new();
|
|
|
|
|
|
|
|
|
|
let update_string = |str| s.push_str(str);
|
|
|
|
|
|
|
|
|
|
exec(update_string);
|
|
|
|
|
|
|
|
|
|
println!("{:?}",s);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn exec<'a, F: Fn(&'a str)>(mut f: F) {
|
|
|
|
|
f("hello")
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>然后运行看看结果:</p>
|
|
|
|
|
<pre><code class="language-console">error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnMut`
|
|
|
|
|
--> src/main.rs:4:26 // 期望闭包实现的是`Fn`特征,但是它只实现了`FnMut`特征
|
|
|
|
|
|
|
|
|
|
|
4 | let update_string = |str| s.push_str(str);
|
|
|
|
|
| ^^^^^^-^^^^^^^^^^^^^^
|
|
|
|
|
| | |
|
|
|
|
|
| | closure is `FnMut` because it mutates the variable `s` here
|
|
|
|
|
| this closure implements `FnMut`, not `Fn` //闭包实现的是FnMut,而不是Fn
|
|
|
|
|
5 |
|
|
|
|
|
6 | exec(update_string);
|
|
|
|
|
| ---- the requirement to implement `Fn` derives from here
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>从报错中很清晰的看出,我们的闭包实现的是 <code>FnMut</code> 特征,需要的是可变借用,但是在 <code>exec</code> 中却给它标注了 <code>Fn</code> 特征,因此产生了不匹配,再来看看正确的不可变借用方式:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let s = "hello, ".to_string();
|
|
|
|
|
|
|
|
|
|
let update_string = |str| println!("{},{}",s,str);
|
|
|
|
|
|
|
|
|
|
exec(update_string);
|
|
|
|
|
|
|
|
|
|
println!("{:?}",s);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn exec<'a, F: Fn(String) -> ()>(f: F) {
|
|
|
|
|
f("world".to_string())
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>在这里,因为无需改变 <code>s</code>,因此闭包中只对 <code>s</code> 进行了不可变借用,那么在 <code>exec</code> 中,将其标记为 <code>Fn</code> 特征就完全正确。</p>
|
|
|
|
|
<h4 id="move-和-fn"><a class="header" href="#move-和-fn">move 和 Fn</a></h4>
|
|
|
|
|
<p>在上面,我们讲到了 <code>move</code> 关键字对于 <code>FnOnce</code> 特征的重要性,但是实际上使用了 <code>move</code> 的闭包依然可以使用 <code>Fn</code> 或 <code>FnMut</code> 特征。</p>
|
|
|
|
|
<p>因为,<strong>一个闭包实现了哪种 Fn 特征取决于该闭包如何使用被捕获的变量,而不是取决于闭包如何捕获它们</strong>。<code>move</code> 本身强调的就是后者,闭包如何捕获变量:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let s = String::new();
|
|
|
|
|
|
|
|
|
|
let update_string = move || println!("{}",s);
|
|
|
|
|
|
|
|
|
|
exec(update_string);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn exec<F: FnOnce()>(f: F) {
|
|
|
|
|
f()
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>我们在上面的闭包中使用了 <code>move</code> 关键字,所以我们的闭包捕获了它,但是由于闭包获取了 <code>s</code> 的所有权,因此该闭包实现了 <code>FnOnce</code> 的特征。</p>
|
|
|
|
|
<p>但是假如我们将代码修改成下面这样,依然可以编译:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let s = String::new();
|
|
|
|
|
|
|
|
|
|
let update_string = move || println!("{}",s);
|
|
|
|
|
|
|
|
|
|
exec(update_string);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn exec<F: Fn()>(f: F) {
|
|
|
|
|
f()
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>奇怪, 明明是闭包实现的是 <code>FnOnce</code> 的特征, 为什么编译器居然允许 <code>Fn</code> 特征通过编译呢?</p>
|
|
|
|
|
<h4 id="三种-fn-的关系"><a class="header" href="#三种-fn-的关系">三种 Fn 的关系</a></h4>
|
|
|
|
|
<p>实际上,一个闭包并不仅仅实现某一种 <code>Fn</code> 特征,规则如下:</p>
|
|
|
|
|
<ul>
|
|
|
|
|
<li>所有的闭包都自动实现了 <code>FnOnce</code> 特征,因此任何一个闭包都至少可以被调用一次</li>
|
|
|
|
|
<li>没有移出所捕获变量的所有权的闭包自动实现了 <code>FnMut</code> 特征</li>
|
|
|
|
|
<li>不需要对捕获变量进行改变的闭包自动实现了 <code>Fn</code> 特征</li>
|
|
|
|
|
</ul>
|
|
|
|
|
<p>用一段代码来简单诠释上述规则:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let s = String::new();
|
|
|
|
|
|
|
|
|
|
let update_string = || println!("{}",s);
|
|
|
|
|
|
|
|
|
|
exec(update_string);
|
|
|
|
|
exec1(update_string);
|
|
|
|
|
exec2(update_string);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn exec<F: FnOnce()>(f: F) {
|
|
|
|
|
f()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn exec1<F: FnMut()>(mut f: F) {
|
|
|
|
|
f()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn exec2<F: Fn()>(f: F) {
|
|
|
|
|
f()
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<p>虽然,闭包只是对 <code>s</code> 进行了不可变借用,实际上,它可以适用于任何一种 <code>Fn</code> 特征:三个 <code>exec</code> 函数说明了一切。强烈建议读者亲自动手试试各种情况下使用的 <code>Fn</code> 特征,更有助于加深这方面的理解。</p>
|
|
|
|
|
<p>关于第二条规则,有如下示例:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021">fn main() {
|
|
|
|
|
let mut s = String::new();
|
|
|
|
|
|
|
|
|
|
let update_string = |str| -> String {s.push_str(str); s };
|
|
|
|
|
|
|
|
|
|
exec(update_string);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn exec<'a, F: FnMut(&'a str) -> String>(mut f: F) {
|
|
|
|
|
f("hello");
|
|
|
|
|
}</code></pre></pre>
|
|
|
|
|
<pre><code class="language-console">5 | let update_string = |str| -> String {s.push_str(str); s };
|
|
|
|
|
| ^^^^^^^^^^^^^^^ - closure is `FnOnce` because it moves the variable `s` out of its environment
|
|
|
|
|
| // 闭包实现了`FnOnce`,因为它从捕获环境中移出了变量`s`
|
|
|
|
|
| |
|
|
|
|
|
| this closure implements `FnOnce`, not `FnMut`
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>此例中,闭包从捕获环境中移出了变量 <code>s</code> 的所有权,因此这个闭包仅自动实现了 <code>FnOnce</code>,未实现 <code>FnMut</code> 和 <code>Fn</code>。再次印证之前讲的<strong>一个闭包实现了哪种 Fn 特征取决于该闭包如何使用被捕获的变量,而不是取决于闭包如何捕获它们</strong>,跟是否使用 <code>move</code> 没有必然联系。</p>
|
|
|
|
|
<p>如果还是有疑惑?没关系,我们来看看这三个特征的简化版源码:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub trait Fn<Args> : FnMut<Args> {
|
|
|
|
|
extern "rust-call" fn call(&self, args: Args) -> Self::Output;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub trait FnMut<Args> : FnOnce<Args> {
|
|
|
|
|
extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub trait FnOnce<Args> {
|
|
|
|
|
type Output;
|
|
|
|
|
|
|
|
|
|
extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>看到没?从特征约束能看出来 <code>Fn</code> 的前提是实现 <code>FnMut</code>,<code>FnMut</code> 的前提是实现 <code>FnOnce</code>,因此要实现 <code>Fn</code> 就要同时实现 <code>FnMut</code> 和 <code>FnOnce</code>,这段源码从侧面印证了之前规则的正确性。</p>
|
|
|
|
|
<p>从源码中还能看出一点:<code>Fn</code> 获取 <code>&self</code>,<code>FnMut</code> 获取 <code>&mut self</code>,而 <code>FnOnce</code> 获取 <code>self</code>。
|
|
|
|
|
在实际项目中,<strong>建议先使用 <code>Fn</code> 特征</strong>,然后编译器会告诉你正误以及该如何选择。</p>
|
|
|
|
|
<h2 id="闭包作为函数返回值"><a class="header" href="#闭包作为函数返回值">闭包作为函数返回值</a></h2>
|
|
|
|
|
<p>看到这里,相信大家对于如何使用闭包作为函数参数,已经很熟悉了,但是如果要使用闭包作为函数返回值,该如何做?</p>
|
|
|
|
|
<p>先来看一段代码:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>fn factory() -> Fn(i32) -> i32 {
|
|
|
|
|
let num = 5;
|
|
|
|
|
|
|
|
|
|
|x| x + num
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let f = factory();
|
|
|
|
|
|
|
|
|
|
let answer = f(1);
|
|
|
|
|
assert_eq!(6, answer);
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>上面这段代码看起来还是蛮正常的,用 <code>Fn(i32) -> i32</code> 特征来代表 <code>|x| x + num</code>,非常合理嘛,肯定可以编译通过, 可惜理想总是难以照进现实,编译器给我们报了一大堆错误,先挑几个重点来看看:</p>
|
|
|
|
|
<pre><code class="language-console">fn factory<T>() -> Fn(i32) -> i32 {
|
|
|
|
|
| ^^^^^^^^^^^^^^ doesn't have a size known at compile-time // 该类型在编译器没有固定的大小
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>Rust 要求函数的参数和返回类型,必须有固定的内存大小,例如 <code>i32</code> 就是 4 个字节,引用类型是 8 个字节,总之,绝大部分类型都有固定的大小,但是不包括特征,因为特征类似接口,对于编译器来说,无法知道它后面藏的真实类型是什么,因为也无法得知具体的大小。</p>
|
|
|
|
|
<p>同样,我们也无法知道闭包的具体类型,该怎么办呢?再看看报错提示:</p>
|
|
|
|
|
<pre><code class="language-console">help: use `impl Fn(i32) -> i32` as the return type, as all return paths are of type `[closure@src/main.rs:11:5: 11:21]`, which implements `Fn(i32) -> i32`
|
|
|
|
|
|
|
|
|
|
|
8 | fn factory<T>() -> impl Fn(i32) -> i32 {
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>嗯,编译器提示我们加一个 <code>impl</code> 关键字,哦,这样一说,读者可能就想起来了,<code>impl Trait</code> 可以用来返回一个实现了指定特征的类型,那么这里 <code>impl Fn(i32) -> i32</code> 的返回值形式,说明我们要返回一个闭包类型,它实现了 <code>Fn(i32) -> i32</code> 特征。</p>
|
|
|
|
|
<p>完美解决,但是,在<a href="https://course.rs/basic/trait/trait.html">特征</a>那一章,我们提到过,<code>impl Trait</code> 的返回方式有一个非常大的局限,就是你只能返回同样的类型,例如:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>fn factory(x:i32) -> impl Fn(i32) -> i32 {
|
|
|
|
|
|
|
|
|
|
let num = 5;
|
|
|
|
|
|
|
|
|
|
if x > 1{
|
|
|
|
|
move |x| x + num
|
|
|
|
|
} else {
|
|
|
|
|
move |x| x - num
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>运行后,编译器报错:</p>
|
|
|
|
|
<pre><code class="language-console">error[E0308]: `if` and `else` have incompatible types
|
|
|
|
|
--> src/main.rs:15:9
|
|
|
|
|
|
|
|
|
|
|
12 | / if x > 1{
|
|
|
|
|
13 | | move |x| x + num
|
|
|
|
|
| | ---------------- expected because of this
|
|
|
|
|
14 | | } else {
|
|
|
|
|
15 | | move |x| x - num
|
|
|
|
|
| | ^^^^^^^^^^^^^^^^ expected closure, found a different closure
|
|
|
|
|
16 | | }
|
|
|
|
|
| |_____- `if` and `else` have incompatible types
|
|
|
|
|
|
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>嗯,提示很清晰:<code>if</code> 和 <code>else</code> 分支中返回了不同的闭包类型,这就很奇怪了,明明这两个闭包长的一样的,好在细心的读者应该回想起来,本章节前面咱们有提到:就算签名一样的闭包,类型也是不同的,因此在这种情况下,就无法再使用 <code>impl Trait</code> 的方式去返回闭包。</p>
|
|
|
|
|
<p>怎么办?再看看编译器提示,里面有这样一行小字:</p>
|
|
|
|
|
<pre><code class="language-console">= help: consider boxing your closure and/or using it as a trait object
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>哦,相信你已经恍然大悟,可以用特征对象!只需要用 <code>Box</code> 的方式即可实现:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>fn factory(x:i32) -> Box<dyn Fn(i32) -> i32> {
|
|
|
|
|
let num = 5;
|
|
|
|
|
|
|
|
|
|
if x > 1{
|
|
|
|
|
Box::new(move |x| x + num)
|
|
|
|
|
} else {
|
|
|
|
|
Box::new(move |x| x - num)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>至此,闭包作为函数返回值就已完美解决,若以后你再遇到报错时,一定要仔细阅读编译器的提示,很多时候,转角都能遇到爱。</p>
|
|
|
|
|
<h2 id="闭包的生命周期"><a class="header" href="#闭包的生命周期">闭包的生命周期</a></h2>
|
|
|
|
|
<p>这块儿内容在进阶生命周期章节中有讲,这里就不再赘述,读者可移步<a href="https://course.rs/advance/lifetime/advance.html#%E9%97%AD%E5%8C%85%E5%87%BD%E6%95%B0%E7%9A%84%E6%B6%88%E9%99%A4%E8%A7%84%E5%88%99">此处</a>进行回顾。</p>
|
|
|
|
|
<h2 id="课后习题"><a class="header" href="#课后习题">课后习题</a></h2>
|
|
|
|
|
<blockquote>
|
|
|
|
|
<p><a href="https://practice-zh.course.rs/functional-programing/closure.html">Rust By Practice</a>,支持代码在线编辑和运行,并提供详细的<a href="https://github.com/sunface/rust-by-practice/blob/master/solutions/functional-programing/closure.md">习题解答</a>。</p>
|
|
|
|
|
</blockquote>
|
|
|
|
|
|
|
|
|
|
<div id="giscus-container"></div>
|
|
|
|
|
</main>
|
|
|
|
|
|
|
|
|
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
|
|
|
|
<!-- Mobile navigation buttons -->
|
|
|
|
|
<a rel="prev" href="../../advance/functional-programing/intro.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
|
|
|
|
<i class="fa fa-angle-left"></i>
|
|
|
|
|
</a>
|
|
|
|
|
|
|
|
|
|
<a rel="next prefetch" href="../../advance/functional-programing/iterator.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
|
|
|
|
<i class="fa fa-angle-right"></i>
|
|
|
|
|
</a>
|
|
|
|
|
|
|
|
|
|
<div style="clear: both"></div>
|
|
|
|
|
</nav>
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<nav class="nav-wide-wrapper" aria-label="Page navigation">
|
|
|
|
|
<a rel="prev" href="../../advance/functional-programing/intro.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
|
|
|
|
<i class="fa fa-angle-left"></i>
|
|
|
|
|
</a>
|
|
|
|
|
|
|
|
|
|
<a rel="next prefetch" href="../../advance/functional-programing/iterator.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
|
|
|
|
<i class="fa fa-angle-right"></i>
|
|
|
|
|
</a>
|
|
|
|
|
</nav>
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<script>
|
|
|
|
|
window.playground_copyable = true;
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<script src="../../ace.js"></script>
|
|
|
|
|
<script src="../../editor.js"></script>
|
|
|
|
|
<script src="../../mode-rust.js"></script>
|
|
|
|
|
<script src="../../theme-dawn.js"></script>
|
|
|
|
|
<script src="../../theme-tomorrow_night.js"></script>
|
|
|
|
|
|
|
|
|
|
<script src="../../elasticlunr.min.js"></script>
|
|
|
|
|
<script src="../../mark.min.js"></script>
|
|
|
|
|
<script src="../../searcher.js"></script>
|
|
|
|
|
|
|
|
|
|
<script src="../../clipboard.min.js"></script>
|
|
|
|
|
<script src="../../highlight.js"></script>
|
|
|
|
|
<script src="../../book.js"></script>
|
|
|
|
|
|
|
|
|
|
<script type="text/javascript" charset="utf-8">
|
|
|
|
|
var pagePath = "advance/functional-programing/closure.md"
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<!-- Custom JS scripts -->
|
|
|
|
|
<script src="../../assets/custom.js"></script>
|
|
|
|
|
<script src="../../assets/bigPicture.js"></script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
</body>
|
|
|
|
|
</html>
|