<!DOCTYPE HTML>
< html lang = "zh-CN" class = "light sidebar-visible" dir = "ltr" >
< head >
<!-- Book generated using mdBook -->
< meta charset = "UTF-8" >
< title > 全模式列表 - 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-78591068.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-219e36e1.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/basic/match-pattern/all-patterns.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 = "全模式列表" > < a class = "header" href = "#全模式列表" > 全模式列表< / a > < / h1 >
< p > 在本书中我们已领略过许多不同类型模式的例子,本节的目标就是把这些模式语法都罗列出来,方便大家检索查阅(模式匹配在我们的开发中会经常用到)。< / p >
< h3 id = "匹配字面值" > < a class = "header" href = "#匹配字面值" > 匹配字面值< / a > < / h3 >
< pre class = "playground" > < code class = "language-rust edition2021" > < span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > let x = 1;
match x {
1 => println!("one"),
2 => println!("two"),
3 => println!("three"),
_ => println!("anything"),
}
< span class = "boring" > }< / span > < / code > < / pre >
< p > 这段代码会打印 < code > one< / code > 因为 < code > x< / code > 的值是 1, 如果希望代码获得特定的具体值, 那么这种语法很有用。< / p >
< h3 id = "匹配命名变量" > < a class = "header" href = "#匹配命名变量" > 匹配命名变量< / a > < / h3 >
< p > 在 < a href = "https://course.rs/basic/match-pattern/match-if-let.html#%E5%8F%98%E9%87%8F%E9%81%AE%E8%94%BD" > match< / a > 中,我们有讲过变量遮蔽的问题,这个在< strong > 匹配命名变量< / strong > 时会遇到:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > fn main() {
let x = Some(5);
let y = 10;
match x {
Some(50) => println!("Got 50"),
Some(y) => println!("Matched, y = {:?}", y),
_ => println!("Default case, x = {:?}", x),
}
println!("at the end: x = {:?}, y = {:?}", x, y);
}< / code > < / pre >
< p > 让我们看看当 < code > match< / code > 语句运行的时候发生了什么。第一个匹配分支的模式并不匹配 < code > x< / code > 中定义的值,所以代码继续执行。< / p >
< p > 第二个匹配分支中的模式引入了一个新变量 < code > y< / code > ,它会匹配任何 < code > Some< / code > 中的值。因为这里的 < code > y< / code > 在 < code > match< / code > 表达式的作用域中,而不是之前 < code > main< / code > 作用域中,所以这是一个新变量,不是开头声明为值 10 的那个 < code > y< / code > 。这个新的 < code > y< / code > 绑定会匹配任何 < code > Some< / code > 中的值,在这里是 < code > x< / code > 中的值。因此这个 < code > y< / code > 绑定了 < code > x< / code > 中 < code > Some< / code > 内部的值。这个值是 5, 所以这个分支的表达式将会执行并打印出 < code > Matched, y = 5< / code > 。< / p >
< p > 如果 < code > x< / code > 的值是 < code > None< / code > 而不是 < code > Some(5)< / code > ,头两个分支的模式不会匹配,所以会匹配模式 < code > _< / code > 。这个分支的模式中没有引入变量 < code > x< / code > ,所以此时表达式中的 < code > x< / code > 会是外部没有被遮蔽的 < code > x< / code > ,也就是 < code > None< / code > 。< / p >
< p > 一旦 < code > match< / code > 表达式执行完毕,其作用域也就结束了,同理内部 < code > y< / code > 的作用域也结束了。最后的 < code > println!< / code > 会打印 < code > at the end: x = Some(5), y = 10< / code > 。< / p >
< p > 如果你不想引入变量遮蔽,可以使用另一个变量名而非 < code > y< / code > ,或者使用匹配守卫(match guard)的方式,稍后在< a href = "#匹配守卫提供的额外条件" > 匹配守卫提供的额外条件< / a > 中会讲解。< / p >
< h3 id = "单分支多模式" > < a class = "header" href = "#单分支多模式" > 单分支多模式< / a > < / h3 >
< p > 在 < code > match< / code > 表达式中,可以使用 < code > |< / code > 语法匹配多个模式,它代表 < strong > 或< / strong > 的意思。例如,如下代码将 < code > x< / code > 的值与匹配分支相比较,第一个分支有 < strong > 或< / strong > 选项,意味着如果 < code > x< / code > 的值匹配此分支的任何一个模式,它就会运行:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > < span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > let x = 1;
match x {
1 | 2 => println!("one or two"),
3 => println!("three"),
_ => println!("anything"),
}
< span class = "boring" > }< / span > < / code > < / pre >
< p > 上面的代码会打印 < code > one or two< / code > 。< / p >
< h3 id = "通过序列--匹配值的范围" > < a class = "header" href = "#通过序列--匹配值的范围" > 通过序列 < code > ..=< / code > 匹配值的范围< / a > < / h3 >
< p > 在< a href = "https://course.rs/basic/base-type/numbers.html#序列range" > 数值类型< / a > 中我们有讲到一个序列语法,该语法不仅可以用于循环中,还能用于匹配模式。< / p >
< p > < code > ..=< / code > 语法允许你匹配一个闭区间序列内的值。在如下代码中,当模式匹配任何在此序列内的值时,该分支会执行:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > < span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > let x = 5;
match x {
1..=5 => println!("one through five"),
_ => println!("something else"),
}
< span class = "boring" > }< / span > < / code > < / pre >
< p > 如果 < code > x< / code > 是 1、2、3、4 或 5, 第一个分支就会匹配。这相比使用 < code > |< / code > 运算符表达相同的意思更为方便;相比 < code > 1..=5< / code > ,使用 < code > |< / code > 则不得不指定 < code > 1 | 2 | 3 | 4 | 5< / code > 这五个值,而使用 < code > ..=< / code > 指定序列就简短的多,比如希望匹配从 1 到 1000 的数字的时候!< / p >
< p > 序列只允许用于数字或字符类型,原因是:它们可以连续,同时编译器在编译期可以检查该序列是否为空,字符和数字值是 Rust 中仅有的可以用于判断是否为空的类型。< / p >
< p > 如下是一个使用字符类型序列的例子:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > < span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > let x = 'c';
match x {
'a'..='j' => println!("early ASCII letter"),
'k'..='z' => println!("late ASCII letter"),
_ => println!("something else"),
}
< span class = "boring" > }< / span > < / code > < / pre >
< p > Rust 知道 < code > 'c'< / code > 位于第一个模式的序列内,所以会打印出 < code > early ASCII letter< / code > 。< / p >
< h3 id = "解构并分解值" > < a class = "header" href = "#解构并分解值" > 解构并分解值< / a > < / h3 >
< p > 也可以使用模式来解构结构体、枚举、元组、数组和引用。< / p >
< h4 id = "解构结构体" > < a class = "header" href = "#解构结构体" > 解构结构体< / a > < / h4 >
< p > 下面代码展示了如何用 < code > let< / code > 解构一个带有两个字段 < code > x< / code > 和 < code > y< / code > 的结构体 < code > Point< / code > : < / p >
< pre class = "playground" > < code class = "language-rust edition2021" > struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 0, y: 7 };
let Point { x: a, y: b } = p;
assert_eq!(0, a);
assert_eq!(7, b);
}< / code > < / pre >
< p > 这段代码创建了变量 < code > a< / code > 和 < code > b< / code > 来匹配结构体 < code > p< / code > 中的 < code > x< / code > 和 < code > y< / code > 字段,这个例子展示了< strong > 模式中的变量名不必与结构体中的字段名一致< / strong > 。不过通常希望变量名与字段名一致以便于理解变量来自于哪些字段。< / p >
< p > 因为变量名匹配字段名是常见的,同时因为 < code > let Point { x: x, y: y } = p;< / code > 中 < code > x< / code > 和 < code > y< / code > 重复了,所以对于匹配结构体字段的模式存在简写:只需列出结构体字段的名称,则模式创建的变量会有相同的名称。下例与上例有着相同行为的代码,不过 < code > let< / code > 模式创建的变量为 < code > x< / code > 和 < code > y< / code > 而不是 < code > a< / code > 和 < code > b< / code > : < / p >
< pre class = "playground" > < code class = "language-rust edition2021" > struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 0, y: 7 };
let Point { x, y } = p;
assert_eq!(0, x);
assert_eq!(7, y);
}< / code > < / pre >
< p > 这段代码创建了变量 < code > x< / code > 和 < code > y< / code > ,与结构体 < code > p< / code > 中的 < code > x< / code > 和 < code > y< / code > 字段相匹配。其结果是变量 < code > x< / code > 和 < code > y< / code > 包含结构体 < code > p< / code > 中的值。< / p >
< p > 也可以使用字面值作为结构体模式的一部分进行解构,而不是为所有的字段创建变量。这允许我们测试一些字段为特定值的同时创建其他字段的变量。< / p >
< p > 下文展示了固定某个字段的匹配方式:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > < span class = "boring" > struct Point {
< / span > < span class = "boring" > x: i32,
< / span > < span class = "boring" > y: i32,
< / span > < span class = "boring" > }
< / span > < span class = "boring" >
< / span > fn main() {
let p = Point { x: 0, y: 7 };
match p {
Point { x, y: 0 } => println!("On the x axis at {}", x),
Point { x: 0, y } => println!("On the y axis at {}", y),
Point { x, y } => println!("On neither axis: ({}, {})", x, y),
}
}< / code > < / pre >
< p > 首先是 < code > match< / code > 第一个分支,指定匹配 < code > y< / code > 为 < code > 0< / code > 的 < code > Point< / code > ;
然后第二个分支在第一个分支之后,匹配 < code > y< / code > 不为 < code > 0< / code > , < code > x< / code > 为 < code > 0< / code > 的 < code > Point< / code > ;
最后一个分支匹配 < code > x< / code > 不为 < code > 0< / code > , < code > y< / code > 也不为 < code > 0< / code > 的 < code > Point< / code > 。< / p >
< p > 在这个例子中,值 < code > p< / code > 因为其 < code > x< / code > 包含 0 而匹配第二个分支,因此会打印出 < code > On the y axis at 7< / code > 。< / p >
< h4 id = "解构枚举" > < a class = "header" href = "#解构枚举" > 解构枚举< / a > < / h4 >
< p > 下面代码以 < code > Message< / code > 枚举为例,编写一个 < code > match< / code > 使用模式解构每一个内部值:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
fn main() {
let msg = Message::ChangeColor(0, 160, 255);
match msg {
Message::Quit => {
println!("The Quit variant has no data to destructure.")
}
Message::Move { x, y } => {
println!(
"Move in the x direction {} and in the y direction {}",
x,
y
);
}
Message::Write(text) => println!("Text message: {}", text),
Message::ChangeColor(r, g, b) => {
println!(
"Change the color to red {}, green {}, and blue {}",
r,
g,
b
)
}
}
}< / code > < / pre >
< p > 这里老生常谈一句话,模式匹配一样要类型相同,因此匹配 < code > Message::Move{1,2}< / code > 这样的枚举值,就必须要用 < code > Message::Move{x,y}< / code > 这样的同类型模式才行。< / p >
< p > 这段代码会打印出 < code > Change the color to red 0, green 160, and blue 255< / code > 。尝试改变 < code > msg< / code > 的值来观察其他分支代码的运行。< / p >
< p > 对于像 < code > Message::Quit< / code > 这样没有任何数据的枚举成员,不能进一步解构其值。只能匹配其字面值 < code > Message::Quit< / code > ,因此模式中没有任何变量。< / p >
< p > 对于另外两个枚举成员,就用相同类型的模式去匹配出对应的值即可。< / p >
< h4 id = "解构嵌套的结构体和枚举" > < a class = "header" href = "#解构嵌套的结构体和枚举" > 解构嵌套的结构体和枚举< / a > < / h4 >
< p > 目前为止,所有的例子都只匹配了深度为一级的结构体或枚举。 < code > match< / code > 也可以匹配嵌套的项!< / p >
< p > 例如使用下面的代码来同时支持 RGB 和 HSV 色彩模式:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > enum Color {
Rgb(i32, i32, i32),
Hsv(i32, i32, i32),
}
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(Color),
}
fn main() {
let msg = Message::ChangeColor(Color::Hsv(0, 160, 255));
match msg {
Message::ChangeColor(Color::Rgb(r, g, b)) => {
println!(
"Change the color to red {}, green {}, and blue {}",
r,
g,
b
)
}
Message::ChangeColor(Color::Hsv(h, s, v)) => {
println!(
"Change the color to hue {}, saturation {}, and value {}",
h,
s,
v
)
}
_ => ()
}
}< / code > < / pre >
< p > < code > match< / code > 第一个分支的模式匹配一个 < code > Message::ChangeColor< / code > 枚举成员,该枚举成员又包含了一个 < code > Color::Rgb< / code > 的枚举成员,最终绑定了 3 个内部的 < code > i32< / code > 值。第二个,就交给亲爱的读者来思考完成。< / p >
< h4 id = "解构结构体和元组" > < a class = "header" href = "#解构结构体和元组" > 解构结构体和元组< / a > < / h4 >
< p > 我们甚至可以用复杂的方式来混合、匹配和嵌套解构模式。如下是一个复杂结构体的例子,其中结构体和元组嵌套在元组中,并将所有的原始类型解构出来:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > < span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > struct Point {
x: i32,
y: i32,
}
let ((feet, inches), Point {x, y}) = ((3, 10), Point { x: 3, y: -10 });
< span class = "boring" > }< / span > < / code > < / pre >
< p > 这种将复杂类型分解匹配的方式,可以让我们单独得到感兴趣的某个值。< / p >
< h4 id = "解构数组" > < a class = "header" href = "#解构数组" > 解构数组< / a > < / h4 >
< p > 对于数组,我们可以用类似元组的方式解构,分为两种情况:< / p >
< p > 定长数组< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > < span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > let arr: [u16; 2] = [114, 514];
let [x, y] = arr;
assert_eq!(x, 114);
assert_eq!(y, 514);
< 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 > let arr: & [u16] = & [114, 514];
if let [x, ..] = arr {
assert_eq!(x, & 114);
}
if let & [.., y] = arr {
assert_eq!(y, 514);
}
let arr: & [u16] = & [];
assert!(matches!(arr, [..]));
assert!(!matches!(arr, [x, ..]));
< span class = "boring" > }< / span > < / code > < / pre >
< h3 id = "忽略模式中的值" > < a class = "header" href = "#忽略模式中的值" > 忽略模式中的值< / a > < / h3 >
< p > 有时忽略模式中的一些值是很有用的,比如在 < code > match< / code > 中的最后一个分支使用 < code > _< / code > 模式匹配所有剩余的值。 你也可以在另一个模式中使用 < code > _< / code > 模式,使用一个以下划线开始的名称,或者使用 < code > ..< / code > 忽略所剩部分的值。< / p >
< h4 id = "使用-_-忽略整个值" > < a class = "header" href = "#使用-_-忽略整个值" > 使用 < code > _< / code > 忽略整个值< / a > < / h4 >
< p > 虽然 < code > _< / code > 模式作为 < code > match< / code > 表达式最后的分支特别有用,但是它的作用还不限于此。例如可以将其用于函数参数中:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > fn foo(_: i32, y: i32) {
println!("This code only uses the y parameter: {}", y);
}
fn main() {
foo(3, 4);
}< / code > < / pre >
< p > 这段代码会完全忽略作为第一个参数传递的值 < code > 3< / code > ,并会打印出 < code > This code only uses the y parameter: 4< / code > 。< / p >
< p > 大部分情况当你不再需要特定函数参数时,最好修改签名不再包含无用的参数。在一些情况下忽略函数参数会变得特别有用,比如实现特征时,当你需要特定类型签名但是函数实现并不需要某个参数时。此时编译器就< strong > 不会警告说存在未使用的函数参数< / strong > ,就跟使用命名参数一样。< / p >
< h4 id = "使用嵌套的-_-忽略部分值" > < a class = "header" href = "#使用嵌套的-_-忽略部分值" > 使用嵌套的 < code > _< / code > 忽略部分值< / a > < / h4 >
< p > 可以在一个模式内部使用 < code > _< / code > 忽略部分值:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > < span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > let mut setting_value = Some(5);
let new_setting_value = Some(10);
match (setting_value, new_setting_value) {
(Some(_), Some(_)) => {
println!("Can't overwrite an existing customized value");
}
_ => {
setting_value = new_setting_value;
}
}
println!("setting is {:?}", setting_value);
< span class = "boring" > }< / span > < / code > < / pre >
< p > 这段代码会打印出 < code > Can't overwrite an existing customized value< / code > 接着是 < code > setting is Some(5)< / code > 。< / p >
< p > 第一个匹配分支,我们不关心里面的值,只关心元组中两个元素的类型,因此对于 < code > Some< / code > 中的值,直接进行忽略。
剩下的形如 < code > (Some(_),None)< / code > , < code > (None, Some(_))< / code > , < code > (None,None)< / code > 形式,都由第二个分支 < code > _< / 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 numbers = (2, 4, 8, 16, 32);
match numbers {
(first, _, third, _, fifth) => {
println!("Some numbers: {}, {}, {}", first, third, fifth)
},
}
< span class = "boring" > }< / span > < / code > < / pre >
< p > 老生常谈:模式匹配一定要类型相同,因此匹配 < code > numbers< / code > 元组的模式,也必须有五个值(元组中元素的数量也属于元组类型的一部分)。< / p >
< p > 这会打印出 < code > Some numbers: 2, 8, 32< / code > , 值 4 和 16 会被忽略。< / p >
< h4 id = "使用下划线开头忽略未使用的变量" > < a class = "header" href = "#使用下划线开头忽略未使用的变量" > 使用下划线开头忽略未使用的变量< / a > < / h4 >
< p > 如果你创建了一个变量却不在任何地方使用它, Rust 通常会给你一个警告,因为这可能会是个 BUG。但是有时创建一个不会被使用的变量是有用的, 比如你正在设计原型或刚刚开始一个项目。这时你希望告诉 Rust 不要警告未使用的变量,为此可以用下划线作为变量名的开头:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > fn main() {
let _x = 5;
let y = 10;
}< / code > < / pre >
< p > 这里得到了警告说未使用变量 < code > y< / code > ,至于 < code > x< / code > 则没有警告。< / p >
< p > 注意, 只使用 < code > _< / code > 和使用以下划线开头的名称有些微妙的不同:比如 < strong > < code > _x< / code > 仍会将值绑定到变量,而 < code > _< / code > 则完全不会绑定< / strong > 。< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > < span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > let s = Some(String::from("Hello!"));
if let Some(_s) = s {
println!("found a string");
}
println!("{:?}", s);
< span class = "boring" > }< / span > < / code > < / pre >
< p > < code > s< / code > 是一个拥有所有权的动态字符串,在上面代码中,我们会得到一个错误,因为 < code > s< / code > 的值会被转移给 < code > _s< / code > ,在 < code > println!< / code > 中再次使用 < code > s< / code > 会报错:< / p >
< pre > < code class = "language-console" > error[E0382]: borrow of partially moved value: `s`
--> src/main.rs:8:22
|
4 | if let Some(_s) = s {
| -- value partially moved here
...
8 | println!("{:?}", s);
| ^ value borrowed here after partial move
< / code > < / pre >
< p > 只使用下划线本身,则并不会绑定值,因为 < code > s< / code > 没有被移动进 < code > _< / code > : < / p >
< pre class = "playground" > < code class = "language-rust edition2021" > < span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > let s = Some(String::from("Hello!"));
if let Some(_) = s {
println!("found a string");
}
println!("{:?}", s);
< span class = "boring" > }< / span > < / code > < / pre >
< h4 id = "用--忽略剩余值" > < a class = "header" href = "#用--忽略剩余值" > 用 < code > ..< / code > 忽略剩余值< / a > < / h4 >
< p > 对于有多个部分的值,可以使用 < code > ..< / code > 语法来只使用部分值而忽略其它值,这样也不用再为每一个被忽略的值都单独列出下划线。< code > ..< / code > 模式会忽略模式中剩余的任何没有显式匹配的值部分。< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > < span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > struct Point {
x: i32,
y: i32,
z: i32,
}
let origin = Point { x: 0, y: 0, z: 0 };
match origin {
Point { x, .. } => println!("x is {}", x),
}
< span class = "boring" > }< / span > < / code > < / pre >
< p > 这里列出了 < code > x< / code > 值,接着使用了 < code > ..< / code > 模式来忽略其它字段,这样的写法要比一一列出其它字段,然后用 < code > _< / code > 忽略简洁的多。< / p >
< p > 还可以用 < code > ..< / code > 来忽略元组中间的某些值:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > fn main() {
let numbers = (2, 4, 8, 16, 32);
match numbers {
(first, .., last) => {
println!("Some numbers: {}, {}", first, last);
},
}
}< / code > < / pre >
< p > 这里用 < code > first< / code > 和 < code > last< / code > 来匹配第一个和最后一个值。< code > ..< / code > 将匹配并忽略中间的所有值。< / p >
< p > 然而使用 < code > ..< / code > 必须是无歧义的。如果期望匹配和忽略的值是不明确的, Rust 会报错。下面代码展示了一个带有歧义的 < code > ..< / code > 例子,因此不能编译:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > fn main() {
let numbers = (2, 4, 8, 16, 32);
match numbers {
(.., second, ..) => {
println!("Some numbers: {}", second)
},
}
}< / code > < / pre >
< p > 如果编译上面的例子,会得到下面的错误:< / p >
< pre > < code class = "language-text" > error: `..` can only be used once per tuple pattern // 每个元组模式只能使用一个 `..`
--> src/main.rs:5:22
|
5 | (.., second, ..) => {
| -- ^^ can only be used once per tuple pattern
| |
| previously used here // 上一次使用在这里
error: could not compile `world_hello` due to previous error ^^
< / code > < / pre >
< p > Rust 无法判断,< code > second< / code > 应该匹配 < code > numbers< / code > 中的第几个元素,因此这里使用两个 < code > ..< / code > 模式,是有很大歧义的!< / p >
< h3 id = "匹配守卫提供的额外条件" > < a class = "header" href = "#匹配守卫提供的额外条件" > 匹配守卫提供的额外条件< / a > < / h3 >
< p > < strong > 匹配守卫< / strong > ( < em > match guard< / em > )是一个位于 < code > match< / code > 分支模式之后的额外 < code > if< / 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 num = Some(4);
match num {
Some(x) if x < 5 => println!("less than five: {}", x),
Some(x) => println!("{}", x),
None => (),
}
< span class = "boring" > }< / span > < / code > < / pre >
< p > 这个例子会打印出 < code > less than five: 4< / code > 。当 < code > num< / code > 与模式中第一个分支匹配时,< code > Some(4)< / code > 可以与 < code > Some(x)< / code > 匹配,接着匹配守卫检查 < code > x< / code > 值是否小于 5, 因为 4 小于 5, 所以第一个分支被选择。< / p >
< p > 相反如果 < code > num< / code > 为 < code > Some(10)< / code > ,因为 10 不小于 5 ,所以第一个分支的匹配守卫为假。接着 Rust 会前往第二个分支,因为这里没有匹配守卫所以会匹配任何 < code > Some< / code > 成员。< / p >
< p > 模式中无法提供类如 < code > if x < 5< / code > 的表达能力,我们可以通过匹配守卫的方式来实现。< / p >
< p > 在< a href = "#匹配命名变量" > 之前< / a > ,我们提到可以使用匹配守卫来解决模式中变量覆盖的问题,那里 < code > match< / code > 表达式的模式中新建了一个变量而不是使用 < code > match< / code > 之外的同名变量。内部变量覆盖了外部变量,意味着此时不能够使用外部变量的值,下面代码展示了如何使用匹配守卫修复这个问题。< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > fn main() {
let x = Some(5);
let y = 10;
match x {
Some(50) => println!("Got 50"),
Some(n) if n == y => println!("Matched, n = {}", n),
_ => println!("Default case, x = {:?}", x),
}
println!("at the end: x = {:?}, y = {}", x, y);
}< / code > < / pre >
< p > 上面代码会打印 < code > Default case, x = Some(5)< / code > 。其中,第二个匹配分支由于没有新建局部变量 < code > y< / code > ,因此在匹配守卫中使用的是外部的 < code > y< / code > 。< / p >
< p > 匹配守卫 < code > if n == y< / code > 并不是一个模式所以没有引入新变量。这个 < code > y< / code > < strong > 正是< / strong > 外部的 < code > y< / code > 而不是新的覆盖变量 < code > y< / code > ,这样就可以通过比较 < code > n< / code > 和 < code > y< / code > 来表达寻找一个与外部 < code > y< / code > 相同的值的概念了。< / p >
< p > 也可以在匹配守卫中使用 < strong > 或< / strong > 运算符 < code > |< / code > 来指定多个模式,< strong > 同时匹配守卫的条件会作用于所有的模式< / strong > 。下面代码展示了匹配守卫与 < code > |< / code > 的优先级。这个例子中看起来好像 < code > if y< / code > 只作用于 < code > 6< / code > ,但实际上匹配守卫 < code > if y< / code > 作用于 < code > 4< / code > 、< code > 5< / code > < strong > 和< / strong > < code > 6< / code > ,在满足 < code > x< / code > 属于 < code > 4 | 5 | 6< / code > 后才会判断 < code > y< / code > 是否为 < code > true< / code > : < / p >
< pre class = "playground" > < code class = "language-rust edition2021" > < span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > let x = 4;
let y = false;
match x {
4 | 5 | 6 if y => println!("yes"),
_ => println!("no"),
}
< span class = "boring" > }< / span > < / code > < / pre >
< p > 这个匹配条件表明此分支只匹配 < code > x< / code > 值为 < code > 4< / code > 、< code > 5< / code > 或 < code > 6< / code > < strong > 同时< / strong > < code > y< / code > 为 < code > true< / code > 的情况。< / p >
< p > 虽然在第一个分支中,< code > x< / code > 匹配了模式 < code > 4< / code > ,但是对于匹配守卫 < code > if y< / code > 来说,因为 < code > y< / code > 是 < code > false< / code > ,因此该守卫条件的值永远是 < code > false< / code > ,也意味着第一个分支永远无法被匹配。< / p >
< p > 下面的文字图解释了匹配守卫作用于多个模式时的优先级规则,第一张是正确的:< / p >
< pre > < code class = "language-text" > (4 | 5 | 6) if y => ...
< / code > < / pre >
< p > 而第二张图是错误的< / p >
< pre > < code class = "language-text" > 4 | 5 | (6 if y) => ...
< / code > < / pre >
< p > 可以通过运行代码时的情况看出这一点:如果匹配守卫只作用于由 < code > |< / code > 运算符指定的值列表的最后一个值,这个分支就会匹配且程序会打印出 < code > yes< / code > 。< / p >
< h2 id = "绑定" > < a class = "header" href = "#绑定" > @绑定< / a > < / h2 >
< p > < code > @< / code > (读作 at) 运算符允许为一个字段绑定另外一个变量。下面例子中, 我们希望测试 < code > Message::Hello< / code > 的 < code > id< / code > 字段是否位于 < code > 3..=7< / code > 范围内,同时也希望能将其值绑定到 < code > id_variable< / code > 变量中以便此分支中相关的代码可以使用它。我们可以将 < code > id_variable< / code > 命名为 < code > id< / code > ,与字段同名,不过出于示例的目的这里选择了不同的名称。< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > < span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > enum Message {
Hello { id: i32 },
}
let msg = Message::Hello { id: 5 };
match msg {
Message::Hello { id: id_variable @ 3..=7 } => {
println!("Found an id in range: {}", id_variable)
},
Message::Hello { id: 10..=12 } => {
println!("Found an id in another range")
},
Message::Hello { id } => {
println!("Found some other id: {}", id)
},
}
< span class = "boring" > }< / span > < / code > < / pre >
< p > 上例会打印出 < code > Found an id in range: 5< / code > 。通过在 < code > 3..=7< / code > 之前指定 < code > id_variable @< / code > ,我们捕获了任何匹配此范围的值并同时将该值绑定到变量 < code > id_variable< / code > 上。< / p >
< p > 第二个分支只在模式中指定了一个范围,< code > id< / code > 字段的值可以是 < code > 10、11 或 12< / code > ,不过这个模式的代码并不知情也不能使用 < code > id< / code > 字段中的值,因为没有将 < code > id< / code > 值保存进一个变量。< / p >
< p > 最后一个分支指定了一个没有范围的变量,此时确实拥有可以用于分支代码的变量 < code > id< / code > ,因为这里使用了结构体字段简写语法。不过此分支中没有像头两个分支那样对 < code > id< / code > 字段的值进行测试:任何值都会匹配此分支。< / p >
< p > 当你既想要限定分支范围,又想要使用分支的变量时,就可以用 < code > @< / code > 来绑定到一个新的变量上,实现想要的功能。< / p >
< h4 id = "前绑定后解构rust-156-新增" > < a class = "header" href = "#前绑定后解构rust-156-新增" > @前绑定后解构(Rust 1.56 新增)< / a > < / h4 >
< p > 使用 < code > @< / code > 还可以在绑定新变量的同时,对目标进行解构:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > #[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
// 绑定新变量 `p`,同时对 `Point` 进行解构
let p @ Point {x: px, y: py } = Point {x: 10, y: 23};
println!("x: {}, y: {}", px, py);
println!("{:?}", p);
let point = Point {x: 10, y: 5};
if let p @ Point {x: 10, y} = point {
println!("x is 10 and y is {} in {:?}", y, p);
} else {
println!("x was not 10 :(");
}
}< / code > < / pre >
< h4 id = "新特性rust-153-新增" > < a class = "header" href = "#新特性rust-153-新增" > @新特性(Rust 1.53 新增)< / a > < / h4 >
< p > 考虑下面一段代码:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > fn main() {
match 1 {
num @ 1 | 2 => {
println!("{}", num);
}
_ => {}
}
}< / code > < / pre >
< p > 编译不通过,是因为 < code > num< / code > 没有绑定到所有的模式上,只绑定了模式 < code > 1< / code > ,你可能会试图通过这个方式来解决:< / p >
< pre class = "playground" > < code class = "language-rust edition2021" > < span class = "boring" > #![allow(unused)]
< / span > < span class = "boring" > fn main() {
< / span > num @ (1 | 2)
< span class = "boring" > }< / span > < / code > < / pre >
< p > 但是,如果你用的是 Rust 1.53 之前的版本,那这种写法会报错,因为编译器不支持。< / p >
< p > 至此,模式匹配的内容已经全部完结,复杂但是详尽,想要一次性全部记住属实不易,因此读者可以先留一个印象,等未来需要时,再来翻阅寻找具体的模式实现方式。< / p >
< h2 id = "课后练习" > < a class = "header" href = "#课后练习" > 课后练习< / a > < / h2 >
< blockquote >
< p > < a href = "https://practice-zh.course.rs/pattern-match/patterns.html" > Rust By Practice< / a > ,支持代码在线编辑和运行,并提供详细的< a href = "https://github.com/sunface/rust-by-practice/blob/master/solutions/pattern-match/patterns.md" > 习题解答< / a > 。< / p >
< / blockquote >
< / main >
< nav class = "nav-wrapper" aria-label = "Page navigation" >
<!-- Mobile navigation buttons -->
< a rel = "prev" href = "../../basic/match-pattern/pattern-match.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 = "../../basic/method.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 = "../../basic/match-pattern/pattern-match.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 = "../../basic/method.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-7d8ae1df.js" > < / script >
< script src = "../../assets/bigPicture-be03f9c8.js" > < / script >
< / div >
< / body >
< / html >