<!DOCTYPE HTML>
< html lang = "zh-CN" class = "light sidebar-visible" 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-de23e50b.svg" >
< link rel = "shortcut icon" href = "../../favicon-8114d1fc.png" >
< link rel = "stylesheet" href = "../../css/variables-8adf115d.css" >
< link rel = "stylesheet" href = "../../css/general-2459343d.css" >
< link rel = "stylesheet" href = "../../css/chrome-ae938929.css" >
< link rel = "stylesheet" href = "../../css/print-9e4910d8.css" media = "print" >
<!-- Fonts -->
< link rel = "stylesheet" href = "../../fonts/fonts-9644e21d.css" >
<!-- Highlight.js Stylesheets -->
< link rel = "stylesheet" id = "mdbook-highlight-css" href = "../../highlight-493f70e1.css" >
< link rel = "stylesheet" id = "mdbook-tomorrow-night-css" href = "../../tomorrow-night-4c0ae647.css" >
< link rel = "stylesheet" id = "mdbook-ayu-highlight-css" href = "../../ayu-highlight-3fdfc3ac.css" >
<!-- Custom theme stylesheets -->
< link rel = "stylesheet" href = "../../theme/style-234bffbf.css" >
<!-- Provide site root and default themes to javascript -->
< script >
const path_to_root = "../../";
const default_light_theme = "light";
const default_dark_theme = "navy";
window.path_to_searchindex_js = "../../searchindex-848c21ce.js";
< / script >
<!-- Start loading toc.js asap -->
< script src = "../../toc-42887675.js" > < / script >
< / head >
< body >
< div id = "mdbook-help-container" >
< div id = "mdbook-help-popup" >
< h2 class = "mdbook-help-title" > Keyboard shortcuts< / h2 >
< div >
< p > Press < kbd > ←< / kbd > or < kbd > →< / kbd > to navigate between chapters< / p >
< p > Press < kbd > S< / kbd > or < kbd > /< / kbd > to search in the book< / p >
< p > Press < kbd > ?< / kbd > to show this help< / p >
< p > Press < kbd > Esc< / kbd > to hide this help< / p >
< / div >
< / div >
< / div >
< div id = "mdbook-body-container" >
<!-- Work around some values being stored in localStorage wrapped in quotes -->
< script >
try {
let theme = localStorage.getItem('mdbook-theme');
let 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 >
const default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? default_dark_theme : default_light_theme;
let theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
const html = document.documentElement;
html.classList.remove('light')
html.classList.add(theme);
html.classList.add("js");
< / script >
< input type = "checkbox" id = "mdbook-sidebar-toggle-anchor" class = "hidden" >
<!-- Hide / unhide sidebar before it is displayed -->
< script >
let sidebar = null;
const sidebar_toggle = document.getElementById("mdbook-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 = false;
}
if (sidebar === 'visible') {
sidebar_toggle.checked = true;
} else {
html.classList.remove('sidebar-visible');
}
< / script >
< nav id = "mdbook-sidebar" class = "sidebar" aria-label = "Table of contents" >
<!-- populated by js -->
< mdbook-sidebar-scrollbox class = "sidebar-scrollbox" > < / mdbook-sidebar-scrollbox >
< noscript >
< iframe class = "sidebar-iframe-outer" src = "../../toc.html" > < / iframe >
< / noscript >
< div id = "mdbook-sidebar-resize-handle" class = "sidebar-resize-handle" >
< div class = "sidebar-resize-indicator" > < / div >
< / div >
< / nav >
< div id = "mdbook-page-wrapper" class = "page-wrapper" >
< div class = "page" >
< div id = "mdbook-menu-bar-hover-placeholder" > < / div >
< div id = "mdbook-menu-bar" class = "menu-bar sticky" >
< div class = "left-buttons" >
< label id = "mdbook-sidebar-toggle" class = "icon-button" for = "mdbook-sidebar-toggle-anchor" title = "Toggle Table of Contents" aria-label = "Toggle Table of Contents" aria-controls = "mdbook-sidebar" >
< span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 448 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M0 96C0 78.3 14.3 64 32 64H416c17.7 0 32 14.3 32 32s-14.3 32-32 32H32C14.3 128 0 113.7 0 96zM0 256c0-17.7 14.3-32 32-32H416c17.7 0 32 14.3 32 32s-14.3 32-32 32H32c-17.7 0-32-14.3-32-32zM448 416c0 17.7-14.3 32-32 32H32c-17.7 0-32-14.3-32-32s14.3-32 32-32H416c17.7 0 32 14.3 32 32z" / > < / svg > < / span >
< / label >
< button id = "mdbook-theme-toggle" class = "icon-button" type = "button" title = "Change theme" aria-label = "Change theme" aria-haspopup = "true" aria-expanded = "false" aria-controls = "mdbook-theme-list" >
< span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 576 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M371.3 367.1c27.3-3.9 51.9-19.4 67.2-42.9L600.2 74.1c12.6-19.5 9.4-45.3-7.6-61.2S549.7-4.4 531.1 9.6L294.4 187.2c-24 18-38.2 46.1-38.4 76.1L371.3 367.1zm-19.6 25.4l-116-104.4C175.9 290.3 128 339.6 128 400c0 3.9 .2 7.8 .6 11.6c1.8 17.5-10.2 36.4-27.8 36.4H96c-17.7 0-32 14.3-32 32s14.3 32 32 32H240c61.9 0 112-50.1 112-112c0-2.5-.1-5-.2-7.5z" / > < / svg > < / span >
< / button >
< ul id = "mdbook-theme-list" class = "theme-popup" aria-label = "Themes" role = "menu" >
< li role = "none" > < button role = "menuitem" class = "theme" id = "mdbook-theme-default_theme" > Auto< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "mdbook-theme-light" > Light< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "mdbook-theme-rust" > Rust< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "mdbook-theme-coal" > Coal< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "mdbook-theme-navy" > Navy< / button > < / li >
< li role = "none" > < button role = "menuitem" class = "theme" id = "mdbook-theme-ayu" > Ayu< / button > < / li >
< / ul >
< button id = "mdbook-search-toggle" class = "icon-button" type = "button" title = "Search (`/`)" aria-label = "Toggle Searchbar" aria-expanded = "false" aria-keyshortcuts = "/ s" aria-controls = "mdbook-searchbar" >
< span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 512 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M416 208c0 45.9-14.9 88.3-40 122.7L502.6 457.4c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0L330.7 376c-34.4 25.2-76.8 40-122.7 40C93.1 416 0 322.9 0 208S93.1 0 208 0S416 93.1 416 208zM208 352c79.5 0 144-64.5 144-144s-64.5-144-144-144S64 128.5 64 208s64.5 144 144 144z" / > < / svg > < / span >
< / 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" >
< span class = fa-svg id = "print-button" > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 512 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M128 0C92.7 0 64 28.7 64 64v96h64V64H354.7L384 93.3V160h64V93.3c0-17-6.7-33.3-18.7-45.3L400 18.7C388 6.7 371.7 0 354.7 0H128zM384 352v32 64H128V384 368 352H384zm64 32h32c17.7 0 32-14.3 32-32V256c0-35.3-28.7-64-64-64H64c-35.3 0-64 28.7-64 64v96c0 17.7 14.3 32 32 32H64v64c0 35.3 28.7 64 64 64H384c35.3 0 64-28.7 64-64V384zm-16-88c-13.3 0-24-10.7-24-24s10.7-24 24-24s24 10.7 24 24s-10.7 24-24 24z" / > < / svg > < / span >
< / a >
< a href = "https://github.com/sunface/rust-course" title = "Git repository" aria-label = "Git repository" >
< span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 496 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z" / > < / svg > < / span >
< / 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" rel = "edit" >
< span class = fa-svg id = "git-edit-button" > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 512 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M421.7 220.3l-11.3 11.3-22.6 22.6-205 205c-6.6 6.6-14.8 11.5-23.8 14.1L30.8 511c-8.4 2.5-17.5 .2-23.7-6.1S-1.5 489.7 1 481.2L38.7 353.1c2.6-9 7.5-17.2 14.1-23.8l205-205 22.6-22.6 11.3-11.3 33.9 33.9 62.1 62.1 33.9 33.9zM96 353.9l-9.3 9.3c-.9 .9-1.6 2.1-2 3.4l-25.3 86 86-25.3c1.3-.4 2.5-1.1 3.4-2l9.3-9.3H112c-8.8 0-16-7.2-16-16V353.9zM453.3 19.3l39.4 39.4c25 25 25 65.5 0 90.5l-14.5 14.5-22.6 22.6-11.3 11.3-33.9-33.9-62.1-62.1L314.3 67.7l11.3-11.3 22.6-22.6 14.5-14.5c25-25 65.5-25 90.5 0z" / > < / svg > < / span >
< / a >
< / div >
< / div >
< div id = "mdbook-search-wrapper" class = "hidden" >
< form id = "mdbook-searchbar-outer" class = "searchbar-outer" >
< div class = "search-wrapper" >
< input type = "search" id = "mdbook-searchbar" name = "searchbar" placeholder = "Search this book ..." aria-controls = "mdbook-searchresults-outer" aria-describedby = "searchresults-header" >
< div class = "spinner-wrapper" >
< span class = fa-svg id = "fa-spin" > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 512 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M304 48c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zm0 416c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zM48 304c26.5 0 48-21.5 48-48s-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48zm464-48c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zM142.9 437c18.7-18.7 18.7-49.1 0-67.9s-49.1-18.7-67.9 0s-18.7 49.1 0 67.9s49.1 18.7 67.9 0zm0-294.2c18.7-18.7 18.7-49.1 0-67.9S93.7 56.2 75 75s-18.7 49.1 0 67.9s49.1 18.7 67.9 0zM369.1 437c18.7 18.7 49.1 18.7 67.9 0s18.7-49.1 0-67.9s-49.1-18.7-67.9 0s-18.7 49.1 0 67.9z" / > < / svg > < / span >
< / div >
< / div >
< / form >
< div id = "mdbook-searchresults-outer" class = "searchresults-outer hidden" >
< div id = "mdbook-searchresults-header" class = "searchresults-header" > < / div >
< ul id = "mdbook-searchresults" >
< / ul >
< / div >
< / div >
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
< script >
document.getElementById('mdbook-sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('mdbook-sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#mdbook-sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
< / script >
< div id = "mdbook-content" class = "content" >
< main >
< h1 id = "闭包-closure" > < a class = "header" href = "#闭包-closure" > 闭包 Closure< / a > < / h1 >
< p > 闭包这个词语由来已久,自上世纪 60 年代就由 < code > Scheme< / code > 语言引进之后,被广泛用于函数式编程语言中,进入 21 世纪后,各种现代化的编程语言也都不约而同地把闭包作为核心特性纳入到语言设计中来。那么到底何为闭包?< / p >
< p > 闭包是< strong > 一种匿名函数,它可以赋值给变量也可以作为参数传递给其它函数,不同于函数的是,它允许捕获调用者作用域中的值< / strong > ,例如:< / p >
< 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 >
< 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 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 >
< 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 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 >
< 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 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 >
< p > 在上面代码中,无论你要修改什么,只要修改闭包 < code > action< / code > 的实现即可,其它地方只负责调用,完美解决了我们的问题!< / p >
< p > Rust 闭包在形式上借鉴了 < code > Smalltalk< / code > 和 < code > Ruby< / code > 语言,与函数最大的不同就是它的参数是通过 < code > |parm1|< / code > 的形式进行声明,如果是多个参数就 < code > |param1, param2,...|< / code > , 下面给出闭包的形式定义:< / p >
< 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 >
< p > 如果只有一个返回表达式的话,定义可以简化为:< / p >
< 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 >
< 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 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 >
< p > 与之相比,不标注类型的闭包声明会更简洁些:< code > let sum = |x, y| x + y< / code > ,需要注意的是,针对 < code > sum< / code > 闭包,如果你只进行了声明,但是没有使用,编译器会提示你为 < code > x, y< / code > 添加类型标注,因为它缺乏必要的上下文:< / p >
< 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 >
< 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 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 >
< p > 可以看出第一行的函数和后面的闭包其实在形式上是非常接近的,同时三种不同的闭包也展示了三种不同的使用方式:省略参数、返回值类型和花括号对。< / p >
< p > 虽然类型推导很好用,但是它不是泛型,< strong > 当编译器推导出一种类型后,它就会一直使用该类型< / strong > : < / p >
< 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 >
< 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 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 >
< 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 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 >
< 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 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 >
< 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 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 >
< 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 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 >
< 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 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 >
< 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 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 >
< ol start = "2" >
< li > < code > FnMut< / code > ,它以可变借用的方式捕获了环境中的值,因此可以修改该值:< / li >
< / ol >
< 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 >
< 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 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 >
< p > 这种写法有点反直觉,相比起来前面的 < code > move< / code > 更符合使用和阅读习惯。但是如果你忽略 < code > update_string< / code > 的类型,仅仅把它当成一个普通变量,那么这种声明就比较合理了。< / p >
< p > 再来看一个复杂点的:< / p >
< 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 >
< 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 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 >
< 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 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 >
< p > 这里取得的是< code > s< / code > 的不可变引用,所以是能< code > Copy< / code > 的。而如果拿到的是< code > s< / code > 的所有权或可变引用,都是不能< code > Copy< / code > 的。我们刚刚的代码就属于第二类,取得的是< code > s< / code > 的可变引用,没有实现< code > Copy< / code > 。< / p >
< 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 >
< ol start = "3" >
< li > < code > Fn< / code > 特征,它以不可变借用的方式捕获环境中的值
让我们把上面的代码中 < code > exec< / code > 的 < code > F< / code > 泛型参数类型修改为 < code > Fn(& 'a str)< / code > : < / li >
< / ol >
< 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 >
< 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 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 >
< 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 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 >
< p > 我们在上面的闭包中使用了 < code > move< / code > 关键字,所以我们的闭包捕获了它,但是由于闭包获取了 < code > s< / code > 的所有权,因此该闭包实现了 < code > FnOnce< / code > 的特征。< / p >
< p > 但是假如我们将代码修改成下面这样,依然可以编译:< / p >
< 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 >
< 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 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 >
< p > 虽然,闭包只是对 < code > s< / code > 进行了不可变借用,实际上,它可以适用于任何一种 < code > Fn< / code > 特征:三个 < code > exec< / code > 函数说明了一切。强烈建议读者亲自动手试试各种情况下使用的 < code > Fn< / code > 特征,更有助于加深这方面的理解。< / p >
< p > 关于第二条规则,有如下示例:< / p >
< 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 > < 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 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 >
< 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 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 >
< 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 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 >
< 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 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 >
< p > 至此,闭包作为函数返回值就已完美解决,若以后你再遇到报错时,一定要仔细阅读编译器的提示,很多时候,转角都能遇到爱。< / p >
< h2 id = "闭包的生命周期" > < a class = "header" href = "#闭包的生命周期" > 闭包的生命周期< / a > < / h2 >
< p > 这块儿内容在进阶生命周期章节中有讲,这里就不再赘述,读者可移步< a href = "https://course.rs/advance/lifetime/advance.html#闭包函数的消除规则" > 此处< / 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 >
< / 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" >
< span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 320 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256 246.6 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z" / > < / svg > < / span >
< / 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" >
< span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 320 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M278.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-160 160c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L210.7 256 73.4 118.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l160 160z" / > < / svg > < / span >
< / 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" >
< span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 320 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256 246.6 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z" / > < / svg > < / span >
< / 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" >
< span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 320 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M278.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-160 160c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L210.7 256 73.4 118.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l160 160z" / > < / svg > < / span >
< / a >
< / nav >
< / div >
< template id = fa-eye > < span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 576 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M288 32c-80.8 0-145.5 36.8-192.6 80.6C48.6 156 17.3 208 2.5 243.7c-3.3 7.9-3.3 16.7 0 24.6C17.3 304 48.6 356 95.4 399.4C142.5 443.2 207.2 480 288 480s145.5-36.8 192.6-80.6c46.8-43.5 78.1-95.4 93-131.1c3.3-7.9 3.3-16.7 0-24.6c-14.9-35.7-46.2-87.7-93-131.1C433.5 68.8 368.8 32 288 32zM432 256c0 79.5-64.5 144-144 144s-144-64.5-144-144s64.5-144 144-144s144 64.5 144 144zM288 192c0 35.3-28.7 64-64 64c-11.5 0-22.3-3-31.6-8.4c-.2 2.8-.4 5.5-.4 8.4c0 53 43 96 96 96s96-43 96-96s-43-96-96-96c-2.8 0-5.6 .1-8.4 .4c5.3 9.3 8.4 20.1 8.4 31.6z" / > < / svg > < / span > < / template >
< template id = fa-eye-slash > < span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 640 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M38.8 5.1C28.4-3.1 13.3-1.2 5.1 9.2S-1.2 34.7 9.2 42.9l592 464c10.4 8.2 25.5 6.3 33.7-4.1s6.3-25.5-4.1-33.7L525.6 386.7c39.6-40.6 66.4-86.1 79.9-118.4c3.3-7.9 3.3-16.7 0-24.6c-14.9-35.7-46.2-87.7-93-131.1C465.5 68.8 400.8 32 320 32c-68.2 0-125 26.3-169.3 60.8L38.8 5.1zM223.1 149.5C248.6 126.2 282.7 112 320 112c79.5 0 144 64.5 144 144c0 24.9-6.3 48.3-17.4 68.7L408 294.5c5.2-11.8 8-24.8 8-38.5c0-53-43-96-96-96c-2.8 0-5.6 .1-8.4 .4c5.3 9.3 8.4 20.1 8.4 31.6c0 10.2-2.4 19.8-6.6 28.3l-90.3-70.8zm223.1 298L373 389.9c-16.4 6.5-34.3 10.1-53 10.1c-79.5 0-144-64.5-144-144c0-6.9 .5-13.6 1.4-20.2L83.1 161.5C60.3 191.2 44 220.8 34.5 243.7c-3.3 7.9-3.3 16.7 0 24.6c14.9 35.7 46.2 87.7 93 131.1C174.5 443.2 239.2 480 320 480c47.8 0 89.9-12.9 126.2-32.5z" / > < / svg > < / span > < / template >
< template id = fa-copy > < span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 512 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z" / > < / svg > < / span > < / template >
< template id = fa-play > < span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 384 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M73 39c-14.8-9.1-33.4-9.4-48.5-.9S0 62.6 0 80V432c0 17.4 9.4 33.4 24.5 41.9s33.7 8.1 48.5-.9L361 297c14.3-8.7 23-24.2 23-41s-8.7-32.2-23-41L73 39z" / > < / svg > < / span > < / template >
< template id = fa-clock-rotate-left > < span class = fa-svg > < svg xmlns = "http://www.w3.org/2000/svg" viewBox = "0 0 512 512" > <!-- ! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --> < path d = "M75 75L41 41C25.9 25.9 0 36.6 0 57.9V168c0 13.3 10.7 24 24 24H134.1c21.4 0 32.1-25.9 17-41l-30.8-30.8C155 85.5 203 64 256 64c106 0 192 86 192 192s-86 192-192 192c-40.8 0-78.6-12.7-109.7-34.4c-14.5-10.1-34.4-6.6-44.6 7.9s-6.6 34.4 7.9 44.6C151.2 495 201.7 512 256 512c141.4 0 256-114.6 256-256S397.4 0 256 0C185.3 0 121.3 28.7 75 75zm181 53c-13.3 0-24 10.7-24 24V256c0 6.4 2.5 12.5 7 17l72 72c9.4 9.4 24.6 9.4 33.9 0s9.4-24.6 0-33.9l-65-65V152c0-13.3-10.7-24-24-24z" / > < / svg > < / span > < / template >
< script >
window.playground_copyable = true;
< / script >
< script src = "../../ace-2a3cd908.js" > < / script >
< script src = "../../mode-rust-2c9d5c9a.js" > < / script >
< script src = "../../editor-16ca416c.js" > < / script >
< script src = "../../theme-dawn-4493f9c8.js" > < / script >
< script src = "../../theme-tomorrow_night-9dbe62a9.js" > < / script >
< script src = "../../elasticlunr-ef4e11c1.min.js" > < / script >
< script src = "../../mark-09e88c2c.min.js" > < / script >
< script src = "../../searcher-c2a407aa.js" > < / script >
< script src = "../../clipboard-1626706a.min.js" > < / script >
< script src = "../../highlight-abc7f01d.js" > < / script >
< script src = "../../book-a0b12cfe.js" > < / script >
<!-- Custom JS scripts -->
< script src = "../../assets/custom-690c9de5.js" > < / script >
< script src = "../../assets/bigPicture-be03f9c8.js" > < / script >
< / div >
< / body >
< / html >