Rust入门教程(一).html 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. <!DOCTYPE html>
  2. <html lang="en-US">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width,initial-scale=1">
  6. <title>Rust入门教程(一) | Rust训练营教程文档</title>
  7. <meta name="generator" content="VuePress 1.9.10">
  8. <link rel="icon" href="/rust_camp_tutorial/logo.png">
  9. <meta name="description" content="DragonOS-Rust camp">
  10. <link rel="preload" href="/rust_camp_tutorial/assets/css/0.styles.7dd9be3e.css" as="style"><link rel="preload" href="/rust_camp_tutorial/assets/js/app.d7ab8f65.js" as="script"><link rel="preload" href="/rust_camp_tutorial/assets/js/2.3dc1b8de.js" as="script"><link rel="preload" href="/rust_camp_tutorial/assets/js/1.7f771cfb.js" as="script"><link rel="preload" href="/rust_camp_tutorial/assets/js/24.2f88b37d.js" as="script"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/10.23a1f579.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/11.c389195a.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/12.1d996921.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/13.4d4410c4.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/14.37ef2a72.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/15.5542c093.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/16.d48fd1ce.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/17.bd8d538c.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/18.6d3b94c1.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/19.eb35cfee.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/20.c11ec329.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/21.db1b5d88.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/22.7714be7b.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/23.7f3a9620.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/25.df99dd5f.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/26.606cfbc8.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/27.928f1e6b.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/28.f61a69ee.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/29.802642cf.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/3.5322f14a.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/30.72f41aed.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/31.e1aa8cbc.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/32.30c1ff3b.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/33.f21667a4.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/4.84e1e480.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/5.f0541060.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/6.dfb06aa0.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/7.7551a9fb.js"><link rel="prefetch" href="/rust_camp_tutorial/assets/js/vendors~docsearch.5e19b665.js">
  11. <link rel="stylesheet" href="/rust_camp_tutorial/assets/css/0.styles.7dd9be3e.css">
  12. </head>
  13. <body>
  14. <div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/rust_camp_tutorial/" class="home-link router-link-active"><img src="logo.png" alt="Rust训练营教程文档" class="logo"> <span class="site-name can-hide">Rust训练营教程文档</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/rust_camp_tutorial/" class="nav-link">
  15. 首页
  16. </a></div> <!----></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/rust_camp_tutorial/" class="nav-link">
  17. 首页
  18. </a></div> <!----></nav> <ul class="sidebar-links"><li><section class="sidebar-group depth-0"><p class="sidebar-heading open"><span>Rust入门教程(一)</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/rust_camp_tutorial/Rust%E6%96%87%E6%A1%A3/Rust%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89.html#rust基本介绍" class="sidebar-link">Rust基本介绍</a><ul class="sidebar-sub-headers"></ul></li><li><a href="/rust_camp_tutorial/Rust%E6%96%87%E6%A1%A3/Rust%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89.html#一、变量与可变性" class="sidebar-link">一、变量与可变性</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/rust_camp_tutorial/Rust%E6%96%87%E6%A1%A3/Rust%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89.html#变量与常量" class="sidebar-link">变量与常量</a></li><li class="sidebar-sub-header"><a href="/rust_camp_tutorial/Rust%E6%96%87%E6%A1%A3/Rust%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89.html#shadowing" class="sidebar-link">Shadowing</a></li></ul></li><li><a href="/rust_camp_tutorial/Rust%E6%96%87%E6%A1%A3/Rust%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89.html#二、数据类型" class="sidebar-link">二、数据类型</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/rust_camp_tutorial/Rust%E6%96%87%E6%A1%A3/Rust%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89.html#标量类型" class="sidebar-link">标量类型</a></li><li class="sidebar-sub-header"><a href="/rust_camp_tutorial/Rust%E6%96%87%E6%A1%A3/Rust%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89.html#复合类型" class="sidebar-link">复合类型</a></li></ul></li><li><a href="/rust_camp_tutorial/Rust%E6%96%87%E6%A1%A3/Rust%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89.html#三、函数" class="sidebar-link">三、函数</a><ul class="sidebar-sub-headers"></ul></li><li><a href="/rust_camp_tutorial/Rust%E6%96%87%E6%A1%A3/Rust%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89.html#四、-控制流" class="sidebar-link">四、 控制流</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/rust_camp_tutorial/Rust%E6%96%87%E6%A1%A3/Rust%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89.html#loop循环" class="sidebar-link">loop循环</a></li><li class="sidebar-sub-header"><a href="/rust_camp_tutorial/Rust%E6%96%87%E6%A1%A3/Rust%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89.html#while循环" class="sidebar-link">while循环</a></li><li class="sidebar-sub-header"><a href="/rust_camp_tutorial/Rust%E6%96%87%E6%A1%A3/Rust%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89.html#for循环" class="sidebar-link">for循环</a></li></ul></li><li><a href="/rust_camp_tutorial/Rust%E6%96%87%E6%A1%A3/Rust%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89.html#五、所有权" class="sidebar-link">*五、所有权</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/rust_camp_tutorial/Rust%E6%96%87%E6%A1%A3/Rust%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89.html#所有权和堆栈" class="sidebar-link">所有权和堆栈</a></li><li class="sidebar-sub-header"><a href="/rust_camp_tutorial/Rust%E6%96%87%E6%A1%A3/Rust%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89.html#引用与借用" class="sidebar-link">引用与借用</a></li></ul></li><li><a href="/rust_camp_tutorial/Rust%E6%96%87%E6%A1%A3/Rust%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89.html#六、切片" class="sidebar-link">六、切片</a><ul class="sidebar-sub-headers"></ul></li></ul></section></li></ul> </aside> <main class="page"> <div class="theme-default-content content__default"><h1 id="rust入门教程-一"><a href="#rust入门教程-一" class="header-anchor">#</a> Rust入门教程(一)</h1> <h2 id="rust基本介绍"><a href="#rust基本介绍" class="header-anchor">#</a> Rust基本介绍</h2> <blockquote><p>Rust 语言是一种高效、可靠的通用高级语言。其高效不仅限于开发效率,它的执行效率也是令人称赞的,是一种少有的兼顾开发效率和执行效率的语言。 ——来自菜鸟教程</p></blockquote> <blockquote><p>高性能 - Rust 速度惊人且内存利用率极高。由于没有运行时和垃圾回收,它能够胜任对性能要求特别高的服务,可以在嵌入式设备上运行,还能轻松和其他语言集成。
  19. 可靠性 - Rust 丰富的类型系统和所有权模型保证了内存安全和线程安全,让您在编译期就能够消除各种各样的错误。
  20. 生产力 - Rust 拥有出色的文档、友好的编译器和清晰的错误提示信息,还集成了一流的工具——包管理器和构建工具,智能地自动补全和类型检验的多编辑器支持, 以及自动格式化代码等等。</p></blockquote> <h2 id="一、变量与可变性"><a href="#一、变量与可变性" class="header-anchor">#</a> 一、变量与可变性</h2> <p>声明变量用 <code>let</code> 关键字,默认情况下该变量是不可变的(immutable)</p> <p>声明变量时在前面添加一个 <code>mut</code> 关键字,便可以使得该关键字可以被修改</p> <h3 id="变量与常量"><a href="#变量与常量" class="header-anchor">#</a> 变量与常量</h3> <p>常量(constant)在绑定值之后也是不可变的,但是它与不可变变量有很多区别:</p> <ul><li>不可以使用 <code>mut</code> 修饰,常量永远都是不可变的</li> <li>声明常量用 <code>const</code> 关键字,它的类型必须被标注</li> <li>常量可以在任何作用域内被声明,包括全局作用域</li> <li>常量只可以绑定到常量表达式,无法绑定到函数的调用结果或只能在运行时才能计算出的值</li></ul> <p>在程序运行期间,常量在其声明的作用域内一直有效.</p> <p>命名规范:Rust 中使用全大写字符,每个单词之间用下划线分隔,例如:<code>MAX_NUM</code>。一个声明的例子:<code>const MAX_NUM: u32 = 100_000</code>。(注:数字中也可以添加下划线增强数字的可读性)</p> <h3 id="shadowing"><a href="#shadowing" class="header-anchor">#</a> Shadowing</h3> <p>可以使用相同的名字声明新的变量,新的变量会 <code>Shadowing(隐藏)</code> 之前声明的同名变量。</p> <p><code>shadow</code> 和把变量标记为 <code>mut</code> 是不一样的:</p> <ul><li>如果不使用 <code>let</code> 关键字,那么重新给非 <code>mut</code> 变量赋值就会编译错误</li> <li>而使用 <code>let</code> 声明的新变量,也是不可变的</li> <li>使用 <code>let</code> 声明的同名变量,<strong>类型可以改变</strong></li></ul> <p>例:</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">let</span> string <span class="token operator">=</span> <span class="token string">&quot;STRING&quot;</span><span class="token punctuation">;</span>
  21. <span class="token keyword">let</span> string <span class="token operator">=</span> string<span class="token punctuation">.</span><span class="token function">len</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  22. </code></pre></div><p>这样将字符串提取出他的长度,而不用单独再开一个新的变量。</p> <h2 id="二、数据类型"><a href="#二、数据类型" class="header-anchor">#</a> 二、数据类型</h2> <p><code>Rust</code> 是静态语言,在编译时必须知道所有变量的类型</p> <ul><li>基于使用的值,编译器通常能够推断出他的具体类型</li> <li>但是如果可能的类型很多,(比如 <code>String</code> 转为整数的 <code>parse</code> 方法)那么就要添加类型的标注,否则会报错</li></ul> <h3 id="标量类型"><a href="#标量类型" class="header-anchor">#</a> 标量类型</h3> <p>一个标量类型代表一个单独的值</p> <p>一共有 <strong>整数类型,浮点类型,布尔类型,字符类型</strong> 四种类型</p> <p><strong>整数类型:</strong></p> <p>没有小数部分,如 <code>u32</code>,<code>i32</code>,<code>i64</code>等,表格如下:</p> <table><thead><tr><th>Length</th> <th>Signed</th> <th>Unsigned</th></tr></thead> <tbody><tr><td>8-bit</td> <td>i8</td> <td>u8</td></tr> <tr><td>16-bit</td> <td>i16</td> <td>u16</td></tr> <tr><td>32-bit</td> <td>i32</td> <td>u32</td></tr> <tr><td>64-bit</td> <td>i64</td> <td>u64</td></tr> <tr><td>arch</td> <td>isize</td> <td>usize</td></tr></tbody></table> <p>其中 <code>isize</code> 和 <code>usize</code> 由计算机架构的位数所决定,主要使用场景是对某种集合进行索引操作</p> <p>除了 <code>byte</code> 类型外,所有数值的字面值都可以加上类型后缀,例如:<code>58u8</code>。其中 <code>Rust</code> 中整数默认值为 <code>i32</code></p> <p><strong>整数溢出</strong></p> <p>将一个 <code>u8</code> 类型的值设置为 <code>256</code>,在调试模式下编译会发生 <code>panic</code>,但是在发布模式(--release)下,编译器不会检查可能导致 <code>panic</code> 的溢出,如果溢出,将会执行 “环绕”,即 256 为 0,257 为 1,不会导致 <code>panic</code></p> <p><strong>浮点类型:</strong></p> <p>包含 <code>f32</code>(单精度) 和 <code>f64</code>(双精度)两种浮点类型,统一采用 <code>IEEE-754</code> 标准。</p> <p>浮点类型的默认类型为 <code>f64</code>.</p> <p><strong>数值操作:</strong></p> <p>和其他语言一致</p> <p><strong>布尔类型:</strong></p> <p>布尔类型有 <code>true</code> 和 <code>false</code> 两个值,占用 1 字节,符号是 <code>bool</code></p> <p><strong>字符类型:</strong></p> <p><code>Rust</code> 语言中使用 <code>char</code> 来表示单个字符,字符的字面值采用单引号,占用 4 字节大小,是 <code>Unicode</code> 的标量值,可以表示比 <code>ASCII</code> 码多得多的内容,例如中文,日文,emoji表情等</p> <p><code>Unicode</code> 标量值的范围是从 <code>U+0000</code> 到 <code>U+D7FF</code>,<code>U+E0000</code> 到 <code>U+10FFFF</code></p> <p>但 Unicode 中没有字符的概念,所以直觉上认为的字符也许与 <code>Rust</code> 中的概念并不相符</p> <h3 id="复合类型"><a href="#复合类型" class="header-anchor">#</a> 复合类型</h3> <p>复合类型可以将多个值放在一个类型里</p> <p>Rust 提供了两种基础的复合类型:元组(Tuple),数组</p> <p><strong>Tuple</strong></p> <p>Tuple 可以将多个类型的多个值放在一个类型里</p> <p>Tuple 长度是固定的,一旦声明就无法改变</p> <p>创建和调用举例:</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">let</span> tup<span class="token punctuation">:</span><span class="token punctuation">(</span><span class="token keyword">u32</span><span class="token punctuation">,</span> <span class="token keyword">i64</span><span class="token punctuation">,</span> <span class="token keyword">f32</span><span class="token punctuation">)</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token number">2022</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">461</span><span class="token punctuation">,</span> <span class="token number">6.2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  23. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{}, {}, {}&quot;</span><span class="token punctuation">,</span> tup<span class="token number">.0</span><span class="token punctuation">,</span> tup<span class="token number">.1</span><span class="token punctuation">,</span> tup<span class="token number">.2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  24. </code></pre></div><p><strong>数组</strong></p> <p>数组是在栈(Stack)上分配的单个块的内存</p> <p>数组也可以将多个值放在一个类型里,但是数组中每个元素类型必须一致,数组长度也是固定,一旦声明不能改变</p> <p>创建和调用举例:</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">let</span> a <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  25. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{}&quot;</span><span class="token punctuation">,</span> arr<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  26. </code></pre></div><p>如果想将数据存放在栈中而不是堆中,或者想保留固定数量的元素,可以使用数组。</p> <p>当然如果希望数组长度变得灵活,可以使用 <code>vector</code></p> <p><strong>数组的类型</strong></p> <p>用 <code>[类型; 长度]</code> 这样的形式表示</p> <p>例</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">let</span> a<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token keyword">i32</span><span class="token punctuation">;</span> <span class="token number">5</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  27. </code></pre></div><p>若数组中元素都相同,则有另一种声明数组的方法:</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">let</span> a <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">;</span> <span class="token number">5</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  28. <span class="token comment">//这就相当于</span>
  29. <span class="token keyword">let</span> a <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  30. </code></pre></div><p>在中括号里先指定初始值,然后是分号,然后是元素个数。</p> <p>使用索引来访问数组元素,如果访问的索引超过数组范围,编译会通过,运行时会报错,<strong>但是 Rust 中不允许继续访问越界的地址</strong>(在 C 语言中是允许的,只不过会输出乱码)</p> <h2 id="三、函数"><a href="#三、函数" class="header-anchor">#</a> 三、函数</h2> <p>声明函数使用 <code>fn</code></p> <p>依照惯例,针对函数和变量名,Rust 使用 <code>snake case</code> 命名规范</p> <ul><li>所有字母都是小写,单词之间用下划线隔开</li> <li>Rust 的函数调用不按照声明顺序执行,即在后面声明的函数也可以在前面调用(这点与 C 语言不同)</li></ul> <p><strong>函数的参数</strong></p> <p>parameter(定义函数的参数),arguments(调用函数的参数)</p> <p>必须声明每个参数的类型</p> <p><strong>函数体中的语句和表达式</strong></p> <ul><li>语句 <code>statement</code> 和表达式 <code>expression</code></li> <li>函数体由一系列语句组成,可选的由一个表达式结束</li> <li>Rust 是一个基于表达式的语言</li> <li>语句是执行一些动作的指令</li> <li>表达式会计算产生一个值</li> <li>函数的定义也是语句</li> <li>语句不返回值,因此不能用 let 将一个语句赋值个一个变量</li></ul> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">let</span> y <span class="token operator">=</span> <span class="token punctuation">{</span>
  31. <span class="token keyword">let</span> x <span class="token operator">=</span> <span class="token number">4</span><span class="token punctuation">;</span>
  32. x <span class="token operator">+</span> <span class="token number">2</span>
  33. <span class="token punctuation">}</span><span class="token punctuation">;</span>
  34. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;y = {}&quot;</span><span class="token punctuation">,</span> y<span class="token punctuation">)</span><span class="token punctuation">;</span>
  35. </code></pre></div><p>这里 let y 后面定义了一个代码块,这个块就是一个表达式,<code>x + 2</code> 后面没有分号,是一个表达式,相当于这个块表达式的返回值,因此最后输出的结果为 <code>y = 6</code>.</p> <p>而如果 <code>x + 2</code> 后面加了分号,这就是一个语句了,语句返回一个空的元组,即返回 <code>()</code>,则输出一个空的元组将会报错</p> <p><strong>函数的返回值</strong></p> <p>在 <code>-&gt;</code> 符号后面声明函数返回值的类型,但是不可以为返回值命名</p> <p>在 Rust 中,返回值通常就是函数体中最后一个表达式的值(大多数函数都是默认使用最后一个表达式作为返回值)</p> <p>若想提前返回,需要使用 <code>return</code> 关键字,并指定一个值</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">main</span> <span class="token punctuation">{</span>
  36. <span class="token keyword">let</span> x <span class="token operator">=</span> <span class="token function">plus_five</span><span class="token punctuation">(</span><span class="token number">12</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  37. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;The function return a num {}&quot;</span><span class="token punctuation">,</span> x<span class="token punctuation">)</span><span class="token punctuation">;</span>
  38. <span class="token punctuation">}</span>
  39. <span class="token keyword">fn</span> <span class="token function-definition function">plus_five</span><span class="token punctuation">(</span>x<span class="token punctuation">:</span> <span class="token keyword">i32</span><span class="token punctuation">)</span> <span class="token punctuation">-&gt;</span> <span class="token keyword">i32</span> <span class="token punctuation">{</span>
  40. x <span class="token operator">+</span> <span class="token number">5</span>
  41. <span class="token punctuation">}</span>
  42. </code></pre></div><p><strong>条件判断</strong></p> <p>只有一点说明:<code>if</code> 条件判断中表达式<strong>必须</strong>是 <code>bool</code> 类型,(C 语言等语言可以将类型转成 bool 再判断,Rust 中不可以)</p> <p>当使用了超过一个 <code>else-if</code> 时,最好使用 <code>match</code> 语句进行重构。例:</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">condition_match</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  43. <span class="token keyword">let</span> x <span class="token operator">=</span> <span class="token number">3</span><span class="token punctuation">;</span>
  44. <span class="token keyword">match</span> x <span class="token operator">%</span> <span class="token number">4</span> <span class="token punctuation">{</span>
  45. <span class="token number">4</span> <span class="token operator">=&gt;</span> <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;The number {} can be divided by 4&quot;</span><span class="token punctuation">,</span> x<span class="token punctuation">)</span><span class="token punctuation">,</span>
  46. <span class="token number">3</span> <span class="token operator">=&gt;</span> <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;The number {} can be divided by 3&quot;</span><span class="token punctuation">,</span> x<span class="token punctuation">)</span><span class="token punctuation">,</span>
  47. <span class="token number">2</span> <span class="token operator">=&gt;</span> <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;The number {} can be divided by 2&quot;</span><span class="token punctuation">,</span> x<span class="token punctuation">)</span><span class="token punctuation">,</span>
  48. _ <span class="token operator">=&gt;</span> <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;The number {} can't be divided by 4; 3 and 2&quot;</span><span class="token punctuation">,</span> x<span class="token punctuation">)</span> <span class="token comment">//_ 表示 default</span>
  49. <span class="token punctuation">}</span>
  50. <span class="token punctuation">}</span>
  51. </code></pre></div><p><strong>在 let 语句中使用 if</strong></p> <p>因为 <code>if</code> 是一个表达式,因此可以将其放在 <code>let</code> 语句等号的右边</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">let</span> condition <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
  52. <span class="token keyword">let</span> x <span class="token operator">=</span> <span class="token keyword">if</span> condition <span class="token punctuation">{</span> <span class="token number">5</span> <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span> <span class="token number">6</span> <span class="token punctuation">}</span><span class="token punctuation">;</span>
  53. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{}&quot;</span><span class="token punctuation">,</span> x<span class="token punctuation">)</span><span class="token punctuation">;</span>
  54. </code></pre></div><p>最后返回 x 的值为 5</p> <h2 id="四、-控制流"><a href="#四、-控制流" class="header-anchor">#</a> 四、 控制流</h2> <p>Rust 提供三种循环:<code>loop</code>、<code>while</code> 和 <code>for</code></p> <h3 id="loop循环"><a href="#loop循环" class="header-anchor">#</a> loop循环</h3> <p>loop 关键字将反复执行一块代码,直到手动停止,或者使用 <code>break</code> 停止</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">branch</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  55. <span class="token keyword">let</span> <span class="token keyword">mut</span> counter <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
  56. <span class="token keyword">let</span> x <span class="token operator">=</span> <span class="token keyword">loop</span> <span class="token punctuation">{</span>
  57. counter <span class="token operator">+=</span> <span class="token number">1</span><span class="token punctuation">;</span>
  58. <span class="token keyword">if</span> counter <span class="token operator">==</span> <span class="token number">10</span> <span class="token punctuation">{</span>
  59. <span class="token keyword">break</span> counter <span class="token operator">*</span> <span class="token number">2</span>
  60. <span class="token punctuation">}</span>
  61. <span class="token punctuation">}</span><span class="token punctuation">;</span>
  62. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;The value of counter is {}&quot;</span><span class="token punctuation">,</span> x<span class="token punctuation">)</span><span class="token punctuation">;</span>
  63. <span class="token punctuation">}</span>
  64. </code></pre></div><p>最后输出结果为 20</p> <h3 id="while循环"><a href="#while循环" class="header-anchor">#</a> while循环</h3> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">fn_while</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  65. <span class="token keyword">let</span> <span class="token keyword">mut</span> number <span class="token operator">=</span> <span class="token number">3</span><span class="token punctuation">;</span>
  66. <span class="token keyword">while</span> number <span class="token operator">!=</span> <span class="token number">0</span> <span class="token punctuation">{</span>
  67. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{}!&quot;</span><span class="token punctuation">,</span> number<span class="token punctuation">)</span><span class="token punctuation">;</span>
  68. number <span class="token operator">=</span> number <span class="token operator">-</span> <span class="token number">1</span><span class="token punctuation">;</span>
  69. <span class="token punctuation">}</span>
  70. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;MOVE! NOW!&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  71. <span class="token punctuation">}</span>
  72. </code></pre></div><h3 id="for循环"><a href="#for循环" class="header-anchor">#</a> for循环</h3> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">fn_for</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  73. <span class="token keyword">let</span> a <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">11</span><span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">,</span> <span class="token number">13</span><span class="token punctuation">,</span> <span class="token number">14</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  74. <span class="token keyword">for</span> elem <span class="token keyword">in</span> a<span class="token punctuation">.</span><span class="token function">iter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  75. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;The value is {}&quot;</span><span class="token punctuation">,</span> elem<span class="token punctuation">)</span><span class="token punctuation">;</span>
  76. <span class="token punctuation">}</span>
  77. <span class="token punctuation">}</span>
  78. </code></pre></div><p><strong>使用 for 循环实现 while 循环</strong></p> <p><code>Range</code> 由标准库提供,指定一个开始数字和结束数字,<code>Range</code> 可以生成他们之间的一个数字(左闭右开),<code>rev</code> 方法可以翻转 <code>Range</code>。例:</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">fn_range_for</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  79. <span class="token keyword">for</span> elem <span class="token keyword">in</span> <span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">..</span><span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">rev</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  80. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{}!&quot;</span><span class="token punctuation">,</span> elem<span class="token punctuation">)</span><span class="token punctuation">;</span>
  81. <span class="token punctuation">}</span>
  82. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;Go!&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  83. <span class="token punctuation">}</span>
  84. </code></pre></div><h2 id="五、所有权"><a href="#五、所有权" class="header-anchor">#</a> *五、所有权</h2> <h3 id="所有权和堆栈"><a href="#所有权和堆栈" class="header-anchor">#</a> 所有权和堆栈</h3> <p>所有权是 Rust 中最独特的特性,它让 Rust 无需 GC 就可以保证内存安全。</p> <p><strong>什么是所有权</strong></p> <ul><li>Rust 的核心就是所有权</li> <li>所有程序在运行时都必须管理它们使用计算机内存的方式
  85. <ul><li>有些语言有垃圾收集机制(GC),在程序运行时,它们会不断寻找不再使用的内存</li> <li>在其他例如 C/C++ 语言中,程序员必须显式地分配和释放内存</li></ul></li> <li>Rust 采用了第三种方式
  86. <ul><li>内存是通过一个所有权系统来管理的,其中包含一组编译器在编译时检查的规则</li> <li>当程序运行时,所有权特性不会减慢程序的运行速度,因为 Rust 对内存的管理相关的工作都提前到了编译时</li></ul></li></ul> <p><strong>堆内存和栈内存</strong></p> <ul><li>所有存储在 Stack 上的数据必须拥有已知的固定的大小</li> <li>编译时大小未知的数据或运行时大小可能发生变化的数据必须存放在 Heap 上</li> <li>Heap 的分配和 C 语言类似,在内存空间中找到一块足够大的空间,然后返回一个指针。这叫做“分配”</li> <li>把值压到 Stack 上不叫“分配”</li> <li>将值压到 Stack 上比在 Heap 上快得多,因为操作系统不需要找用来存储数据的空间,那个位置永远在 Stack 最顶端</li></ul> <p><strong>访问数据</strong></p> <ul><li>访问 Heap 的速度比 Stack 慢,因为要通过指针才能找到</li> <li>在 Heap 上分配大量空间也是需要很多时间的</li></ul> <p><strong>所有权解决的问题</strong></p> <ul><li>跟踪代码的哪些部分正在使用 Heap 的哪些数据</li> <li>最小化 Heap 上的重复数据量</li> <li>清理 Heap 上未使用的空间以避免空间不足</li></ul> <p><strong>所有权规则</strong></p> <ul><li>每个值都有一个变量,这个变量是这个值的所有者</li> <li>每个值同时只能拥有一个所有者</li> <li>当所有者超出作用域(Scope)时,该值将被删除</li></ul> <p><strong>String</strong></p> <ul><li>在 Heap 上分配,能够存储在编译时未知数量的文本</li> <li>使用 <code>from</code> 函数从字符串字面值创建出 <code>String</code> 类型</li> <li><code>let s = String::from(&quot;Cherry&quot;);</code></li> <li>这类字符串是可以被修改的</li></ul> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  87. <span class="token keyword">let</span> <span class="token keyword">mut</span> s <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;Hello&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  88. s <span class="token operator">+=</span> <span class="token string">&quot;, Rust&quot;</span><span class="token punctuation">;</span>
  89. s<span class="token punctuation">.</span><span class="token function">push_str</span><span class="token punctuation">(</span><span class="token string">&quot;, Rust&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  90. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{}&quot;</span><span class="token punctuation">,</span> s<span class="token punctuation">)</span><span class="token punctuation">;</span>
  91. <span class="token punctuation">}</span>
  92. </code></pre></div><ul><li>字符串字面值,在编译时就知道它的内容了,其文本内容直接被硬编码到最终的可执行文件里——速度快、高效。是因为其不可变性。</li> <li>String类型,为了支持可变性,需要在 heap 上分配内存来保存编译时未知的文本内容:操作系统必须在运行时来请求内存。这步通过调用<code>String:from</code> 来实现</li> <li>当用完String 之后,需要使用某种方式将内存返回给操作系统这步,在拥有 GC 的语言中,GC 会跟踪并清理不再使用的内存。没有 GC,就需要我们去识别内存何时不再使用,并调用代码将它返回。―如果忘了,那就浪费内存。
  93. <ul><li>如果提前做了,变量就会非法</li> <li>如果做了两次,也是 Bug。必须一次分配对应一次释放</li></ul></li></ul> <p>但是 Rust 采用了不同的方式:对于某个值来说,当拥有它的变量走出作用域时,内存会自动交还给操作系统</p> <p><code>drop</code> 函数,当变量走出作用域时,会调用这个函数</p> <p><strong>变量与数据交互的方式:Move</strong></p> <ul><li><p>String 的组成由三部分组成:指向数据的指针、长度和容量</p></li> <li><p>这些数据放在 Stack 中</p></li> <li><p>字符串数据存放在 Heap 中</p></li> <li><p>长度 len,就是存放字符串内容所需的字节数</p></li> <li><p>容量 capacity 指的是 String 从系统中获得内存的总字节数</p></li></ul> <p><img src="https://raw.githubusercontent.com/CherryYang05/PicGo-image/master/images/20220511181243.png" alt="String的组成"></p> <p>当把 s1 赋值给 s2 时,String 的数据被复制了一份,这实际上只复制了指针、长度和容量这一数据,在堆中的数据并没有被复制。</p> <p><img src="https://raw.githubusercontent.com/CherryYang05/PicGo-image/master/images/20220511202210.png" alt="String浅拷贝"></p> <p>因此当变量离开作用域的时候,Rust 会自动调用 drop 函数,并将变量使用的 heap 内存释放掉。而在 s1 和 s2 都离开作用域的时候,它们都会尝试释放相同的内存,这时就出现了严重的<code>二次释放(double free)bug</code></p> <p>为了保证内存安全,Rust 中没有尝试复制堆中被分配的内存,Rust 让 s1 失效:当 s1 离开作用域的时候,Rust 不需要释放任何东西</p> <p>当 s2 创建之后再使用 s1 的效果由下例展示:</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">test02</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  94. <span class="token keyword">let</span> s1 <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;Owner of Rust#&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  95. <span class="token keyword">let</span> s2 <span class="token operator">=</span> s1<span class="token punctuation">;</span>
  96. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{}&quot;</span><span class="token punctuation">,</span> s1<span class="token punctuation">)</span><span class="token punctuation">;</span>
  97. <span class="token punctuation">}</span>
  98. </code></pre></div><p>当创建 s2 之后,将 s1 的值赋值给 s2 之后,编译器会报如下的错:</p> <div class="language-rust extra-class"><pre class="language-rust"><code>➜ ~<span class="token operator">/</span><span class="token class-name">Code</span><span class="token operator">/</span>rust<span class="token operator">/</span>owner git<span class="token punctuation">:</span><span class="token punctuation">(</span>master<span class="token punctuation">)</span> ✗ cargo run
  99. <span class="token class-name">Compiling</span> owner v0<span class="token number">.1</span><span class="token punctuation">.</span><span class="token number">0</span> <span class="token punctuation">(</span><span class="token operator">/</span>home<span class="token operator">/</span>cherry<span class="token operator">/</span><span class="token class-name">Code</span><span class="token operator">/</span>rust<span class="token operator">/</span>owner<span class="token punctuation">)</span>
  100. warning<span class="token punctuation">:</span> unused variable<span class="token punctuation">:</span> `s2`
  101. <span class="token operator">-</span><span class="token punctuation">-&gt;</span> src<span class="token operator">/</span>main<span class="token punctuation">.</span>rs<span class="token punctuation">:</span><span class="token number">22</span><span class="token punctuation">:</span><span class="token number">9</span>
  102. <span class="token operator">|</span>
  103. <span class="token number">22</span> <span class="token operator">|</span> <span class="token keyword">let</span> s2 <span class="token operator">=</span> s1<span class="token punctuation">;</span>
  104. <span class="token operator">|</span> <span class="token operator">^</span><span class="token operator">^</span> help<span class="token punctuation">:</span> <span class="token keyword">if</span> this is intentional<span class="token punctuation">,</span> prefix it with an underscore<span class="token punctuation">:</span> `_s2`
  105. <span class="token operator">|</span>
  106. <span class="token operator">=</span> note<span class="token punctuation">:</span> `<span class="token attribute attr-name">#[warn(unused_variables)]</span>` on by default
  107. error<span class="token punctuation">[</span><span class="token constant">E0382</span><span class="token punctuation">]</span><span class="token punctuation">:</span> borrow of moved value<span class="token punctuation">:</span> `s1`
  108. <span class="token operator">-</span><span class="token punctuation">-&gt;</span> src<span class="token operator">/</span>main<span class="token punctuation">.</span>rs<span class="token punctuation">:</span><span class="token number">24</span><span class="token punctuation">:</span><span class="token number">20</span>
  109. <span class="token operator">|</span>
  110. <span class="token number">20</span> <span class="token operator">|</span> <span class="token keyword">let</span> s1 <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;Owner of Rust#&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  111. <span class="token operator">|</span> <span class="token operator">-</span><span class="token operator">-</span> <span class="token keyword">move</span> occurs because `s1` has <span class="token keyword">type</span> `<span class="token class-name">String</span>`<span class="token punctuation">,</span> which does not implement the `<span class="token class-name">Copy</span>` <span class="token keyword">trait</span>
  112. <span class="token type-definition class-name">21</span> <span class="token operator">|</span>
  113. <span class="token number">22</span> <span class="token operator">|</span> <span class="token keyword">let</span> s2 <span class="token operator">=</span> s1<span class="token punctuation">;</span>
  114. <span class="token operator">|</span> <span class="token operator">-</span><span class="token operator">-</span> value moved here
  115. <span class="token number">23</span> <span class="token operator">|</span>
  116. <span class="token number">24</span> <span class="token operator">|</span> <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{}&quot;</span><span class="token punctuation">,</span> s1<span class="token punctuation">)</span><span class="token punctuation">;</span>
  117. <span class="token operator">|</span> <span class="token operator">^</span><span class="token operator">^</span> value borrowed here after <span class="token keyword">move</span>
  118. <span class="token operator">|</span>
  119. <span class="token operator">=</span> note<span class="token punctuation">:</span> this error originates <span class="token keyword">in</span> the <span class="token keyword">macro</span> `<span class="token variable">$crate</span><span class="token punctuation">::</span>format_args_nl` <span class="token punctuation">(</span><span class="token keyword">in</span> <span class="token class-name">Nightly</span> builds<span class="token punctuation">,</span> run with <span class="token operator">-</span><span class="token class-name">Z</span> <span class="token keyword">macro</span><span class="token operator">-</span>backtrace <span class="token keyword">for</span> more info<span class="token punctuation">)</span>
  120. <span class="token class-name">For</span> more information about this error<span class="token punctuation">,</span> <span class="token keyword">try</span> `rustc <span class="token operator">-</span><span class="token operator">-</span>explain <span class="token constant">E0382</span>`<span class="token punctuation">.</span>
  121. warning<span class="token punctuation">:</span> `owner` <span class="token punctuation">(</span>bin <span class="token string">&quot;owner&quot;</span><span class="token punctuation">)</span> generated <span class="token number">1</span> warning
  122. error<span class="token punctuation">:</span> could not compile `owner` due to previous error<span class="token punctuation">;</span> <span class="token number">1</span> warning emitted
  123. </code></pre></div><p>也许这跟浅拷贝(shadow copy)比较类似,但是 Rust 同时还让 s1 失效了,因此用一个新的术语 <code>move</code> 来形容。同时 Rust 也隐含了一个设计原则:即 Rust 不会自动创建数据的深拷贝,通俗的说就是一块内存只能有一个变量进行操作。就运行时性能而言,任何自动赋值操作都是廉价的。</p> <p><strong>变量与数据交互的方式:Clone</strong></p> <p>要想对 heap 上面的数据进行深拷贝,可以使用 <code>clone</code> 方法,<code>clone</code> 是 <code>copy</code> 子集。例子如下:</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">test02</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  124. <span class="token keyword">let</span> s1 <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;Owner of Rust#&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  125. <span class="token keyword">let</span> s2 <span class="token operator">=</span> s1<span class="token punctuation">.</span>clone<span class="token punctuation">;</span>
  126. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{}&quot;</span><span class="token punctuation">,</span> s1<span class="token punctuation">)</span><span class="token punctuation">;</span>
  127. <span class="token punctuation">}</span>
  128. </code></pre></div><p>Stack上的数据:复制</p> <ul><li>Copy trait,可以用于像整数这样完全存放在stack上面的类型</li> <li>如果一个类型实现了 Copy 这个 trait,那么旧的变量在赋值后仍然可用</li> <li>如果一个类型或者该类型的一部分实现了 Drop trait,那么 Rust 不允许让它再去实现 Copy trait 了</li></ul> <p>标准库文档里有说,std::ops::Drop 这个 trait 与 Copy_trait 无法共存于一个类型,因为在 Move 时,若发生 Copy 行为,Copy 行为是隐式的,因为是隐式的,编译器很难预测什么时候调用 Drop 函数,而实现了 Clone_trait 的,因为 clone 是显式的,需要 a.clone() 这样,那么编译器就能通过这种显式的 clone,确定被 clone 的变量的位置,决定何时调用 drop 函数。</p> <p><strong>一些拥有 Copy trait 的类型</strong></p> <ul><li>任何简单标量的组合类型都可以是 Copy 的</li> <li>任何需要分配内存或某种资源的都不是 Copy 的</li> <li>一些拥有 Copy trait 的类型:–所有的整数类型
  129. <ul><li>例如 u32-bool</li> <li>char</li> <li>所有的浮点类型,例如 f64</li> <li>Tuple(元组),如果其所有的字段都是 Copy 的
  130. <ul><li>(i32, i32) 是</li> <li>(i32, String) 不是</li></ul></li></ul></li></ul> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">test02</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  131. <span class="token keyword">let</span> s1 <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;Owner of Rust#&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  132. <span class="token function">take_ownership</span><span class="token punctuation">(</span>s1<span class="token punctuation">)</span><span class="token punctuation">;</span>
  133. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{}&quot;</span><span class="token punctuation">,</span> s1<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//报错,因为 s1 被 take_ownership 调用过后就会释放掉</span>
  134. <span class="token keyword">let</span> x <span class="token operator">=</span> <span class="token number">20</span><span class="token punctuation">;</span>
  135. <span class="token function">makes_copy</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span><span class="token punctuation">;</span>
  136. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{}&quot;</span><span class="token punctuation">,</span> x<span class="token punctuation">)</span><span class="token punctuation">;</span>
  137. <span class="token punctuation">}</span>
  138. <span class="token keyword">fn</span> <span class="token function-definition function">take_ownership</span><span class="token punctuation">(</span>string<span class="token punctuation">:</span> <span class="token class-name">String</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  139. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{}&quot;</span><span class="token punctuation">,</span> string<span class="token punctuation">)</span><span class="token punctuation">;</span>
  140. <span class="token punctuation">}</span>
  141. <span class="token keyword">fn</span> <span class="token function-definition function">makes_copy</span><span class="token punctuation">(</span>num<span class="token punctuation">:</span> <span class="token keyword">u32</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  142. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{}&quot;</span><span class="token punctuation">,</span> num<span class="token punctuation">)</span><span class="token punctuation">;</span>
  143. <span class="token punctuation">}</span>
  144. </code></pre></div><p><strong>返回值与作用域</strong></p> <p>函数在返回值的过程中也会发生所有权的转移,下面的例子可以很好的帮助理解所有权这一概念:</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">test03</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  145. <span class="token keyword">let</span> s1 <span class="token operator">=</span> <span class="token function">give_ownership</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  146. <span class="token keyword">let</span> s2 <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;Rust&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  147. <span class="token keyword">let</span> s3 <span class="token operator">=</span> <span class="token function">take_and_give_ownership</span><span class="token punctuation">(</span>s2<span class="token punctuation">)</span><span class="token punctuation">;</span>
  148. <span class="token punctuation">}</span>
  149. <span class="token keyword">fn</span> <span class="token function-definition function">give_ownership</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">-&gt;</span> <span class="token class-name">String</span> <span class="token punctuation">{</span>
  150. <span class="token keyword">let</span> string <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;$Rust$&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  151. string
  152. <span class="token punctuation">}</span>
  153. <span class="token keyword">fn</span> <span class="token function-definition function">take_and_give_ownership</span><span class="token punctuation">(</span>string<span class="token punctuation">:</span> <span class="token class-name">String</span><span class="token punctuation">)</span> <span class="token punctuation">-&gt;</span> <span class="token class-name">String</span> <span class="token punctuation">{</span>
  154. string
  155. <span class="token punctuation">}</span>
  156. </code></pre></div><p>其中 s2 在函数 <code>take_and_give_ownership</code> 调用后,所有权转移到了函数中,随着函数执行完,s2 的所有权也没有了。实际上函数的作用就是获得 s2 的所有权,然后这个所有权又返回给了 s3.</p> <p>一个变量的所有权总是遵循同样的模式:</p> <ul><li>把一个值赋给其它变量时就会发生移动</li> <li>当一个包含 heap 数据的变量离开作用域时,它的值就会被drop 函数清理,除非数据的所有权移动到另一个变量上</li></ul> <p>那么如何让函数使用某个值,而不获得其所有权?例子如下:</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">test04</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  157. <span class="token keyword">let</span> s1 <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;Welcome!&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  158. <span class="token keyword">let</span> <span class="token punctuation">(</span>s2<span class="token punctuation">,</span> len<span class="token punctuation">)</span> <span class="token operator">=</span> <span class="token function">calc_len</span><span class="token punctuation">(</span>s1<span class="token punctuation">)</span><span class="token punctuation">;</span>
  159. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;The string {}'s length is {}.&quot;</span><span class="token punctuation">,</span> s2<span class="token punctuation">,</span> len<span class="token punctuation">)</span><span class="token punctuation">;</span>
  160. <span class="token punctuation">}</span>
  161. <span class="token keyword">fn</span> <span class="token function-definition function">calc_len</span><span class="token punctuation">(</span><span class="token keyword">str</span><span class="token punctuation">:</span> <span class="token class-name">String</span><span class="token punctuation">)</span> <span class="token punctuation">-&gt;</span> <span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token keyword">usize</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  162. <span class="token keyword">let</span> len <span class="token operator">=</span> <span class="token keyword">str</span><span class="token punctuation">.</span><span class="token function">len</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  163. <span class="token punctuation">(</span><span class="token keyword">str</span><span class="token punctuation">,</span> len<span class="token punctuation">)</span>
  164. <span class="token punctuation">}</span>
  165. </code></pre></div><p>我们将 s1 作为参数传递进去,返回一个包含 String 和 usize 类型的元组,这样就将 s1 的所有权转移给了 s2。</p> <p>那么如果不要传递参数能做到吗?下一节进行介绍。</p> <h3 id="引用与借用"><a href="#引用与借用" class="header-anchor">#</a> 引用与借用</h3> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">test05</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  166. <span class="token keyword">let</span> s <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;引用与借用&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  167. <span class="token keyword">let</span> len <span class="token operator">=</span> <span class="token function">calc_len_2</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>s<span class="token punctuation">)</span><span class="token punctuation">;</span>
  168. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;The string {}'s length is {}.&quot;</span><span class="token punctuation">,</span> s<span class="token punctuation">,</span> len<span class="token punctuation">)</span><span class="token punctuation">;</span>
  169. <span class="token punctuation">}</span>
  170. <span class="token keyword">fn</span> <span class="token function-definition function">calc_len_2</span><span class="token punctuation">(</span><span class="token keyword">str</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token class-name">String</span><span class="token punctuation">)</span> <span class="token punctuation">-&gt;</span> <span class="token keyword">usize</span> <span class="token punctuation">{</span>
  171. <span class="token keyword">str</span><span class="token punctuation">.</span><span class="token function">len</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  172. <span class="token punctuation">}</span>
  173. </code></pre></div><ul><li>参数类型是 <code>&amp;String</code> 而不是 <code>String</code></li> <li><code>&amp;</code>就表示引用,允许引用某些值而不得到其所有权</li></ul> <p><img src="https://raw.githubusercontent.com/CherryYang05/PicGo-image/master/images/20220512190841.png" alt="引用"></p> <p>注:Rust 中解引用的符号和 C/C++ 中是一样的,都是 <code>*</code>.</p> <ul><li>把引用作为函数参数的行为就叫<strong>借用</strong></li> <li>和变量一样,引用也是默认不能被修改的</li> <li>若要使其能够修改,需要加上 <code>mut</code> 关键字</li></ul> <p>例子如下:</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">test05</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  174. <span class="token keyword">let</span> <span class="token keyword">mut</span> s <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;引用&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  175. <span class="token keyword">let</span> len <span class="token operator">=</span> <span class="token function">calc_len_2</span><span class="token punctuation">(</span><span class="token operator">&amp;</span><span class="token keyword">mut</span> s<span class="token punctuation">)</span><span class="token punctuation">;</span>
  176. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;The string {}'s length is {}.&quot;</span><span class="token punctuation">,</span> s<span class="token punctuation">,</span> len<span class="token punctuation">)</span><span class="token punctuation">;</span>
  177. <span class="token punctuation">}</span>
  178. <span class="token keyword">fn</span> <span class="token function-definition function">calc_len_2</span><span class="token punctuation">(</span><span class="token keyword">str</span><span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token keyword">mut</span> <span class="token class-name">String</span><span class="token punctuation">)</span> <span class="token punctuation">-&gt;</span> <span class="token keyword">usize</span> <span class="token punctuation">{</span>
  179. <span class="token keyword">str</span><span class="token punctuation">.</span><span class="token function">push_str</span><span class="token punctuation">(</span><span class="token string">&quot;与借用&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  180. <span class="token keyword">str</span><span class="token punctuation">.</span><span class="token function">len</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  181. <span class="token punctuation">}</span>
  182. </code></pre></div><p>若修改了一个引用对象,则会报这样的错误:</p> <p><code>cannot borrow *str as mutable, as it is behind a &amp; reference</code></p> <p><strong>可变引用</strong></p> <p>可变引用有一个重要的限制:在特定作用域内,对某一块数据,只能有一个可变的引用。</p> <ul><li>这样做的好处是可在编译时防止数据竞争</li></ul> <p>以下三种行为下会发生数据竞争:</p> <ul><li>两个或多个指针同时访问同一个数据一至少有一个指针用于写入数据</li> <li>没有使用任何机制来同步对数据的访问</li> <li>可以通过创建新的作用域,来允许非同时的创建多个可变引用</li></ul> <p>例:</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">test06</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  183. <span class="token keyword">let</span> <span class="token keyword">mut</span> s <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;Hello&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  184. <span class="token keyword">let</span> s1 <span class="token operator">=</span> <span class="token operator">&amp;</span><span class="token keyword">mut</span> s<span class="token punctuation">;</span>
  185. <span class="token keyword">let</span> s2 <span class="token operator">=</span> <span class="token operator">&amp;</span><span class="token keyword">mut</span> s<span class="token punctuation">;</span>
  186. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{}, {}&quot;</span><span class="token punctuation">,</span> s1<span class="token punctuation">,</span> s2<span class="token punctuation">)</span><span class="token punctuation">;</span>
  187. <span class="token punctuation">}</span>
  188. </code></pre></div><p>这里 s1 和 s2 同时对可变变量 s 进行了引用,就会报这样的错误:<code>cannot borrow s as mutable more than once at a time</code></p> <p>通过创建新的作用域,可以允许非同时的创建多个可变引用</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">test06</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  189. <span class="token keyword">let</span> <span class="token keyword">mut</span> s <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;Hello&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  190. <span class="token punctuation">{</span>
  191. <span class="token keyword">let</span> s1 <span class="token operator">=</span> <span class="token operator">&amp;</span><span class="token keyword">mut</span> s<span class="token punctuation">;</span>
  192. <span class="token punctuation">}</span>
  193. <span class="token keyword">let</span> s2 <span class="token operator">=</span> <span class="token operator">&amp;</span><span class="token keyword">mut</span> s<span class="token punctuation">;</span>
  194. <span class="token punctuation">}</span>
  195. </code></pre></div><p><strong>另一个限制</strong></p> <ul><li>不可以同时拥有一个可变引用和一个不变的引用(因为不可变引用的作用就是不让值改变,被可变引用改变后,不可变引用就失去了其作用)</li> <li>多个不变的引用是可以的</li></ul> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">test06</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  196. <span class="token keyword">let</span> <span class="token keyword">mut</span> s <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;Hello&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  197. <span class="token keyword">let</span> s2 <span class="token operator">=</span> <span class="token operator">&amp;</span>s<span class="token punctuation">;</span>
  198. <span class="token keyword">let</span> s3 <span class="token operator">=</span> <span class="token operator">&amp;</span>s<span class="token punctuation">;</span>
  199. <span class="token keyword">let</span> s4 <span class="token operator">=</span> <span class="token operator">&amp;</span><span class="token keyword">mut</span> s<span class="token punctuation">;</span> <span class="token comment">//报错</span>
  200. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{} {} {}&quot;</span><span class="token punctuation">,</span> s2<span class="token punctuation">,</span> s3<span class="token punctuation">,</span> s4<span class="token punctuation">)</span><span class="token punctuation">;</span>
  201. <span class="token punctuation">}</span>
  202. </code></pre></div><p>这样便会报错:<code>cannot borrow s as mutable because it is also borrowed as immutable</code></p> <p><strong>悬空引用 Dangling References</strong></p> <p>悬空指针(Dangling Pointer): 一个指针引用了内存中的某个地址,而这块内存可能已经释放并分配给其它人使用了。</p> <ul><li>在Rust里,编译器可保证引用永远都不是悬空引用</li> <li>如果你引用了某些数据,编译器将保证在引用离开作用域之前数据不会离开作用域</li></ul> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">test07</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  203. <span class="token keyword">let</span> r <span class="token operator">=</span> <span class="token function">dangle</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  204. <span class="token punctuation">}</span>
  205. <span class="token keyword">fn</span> <span class="token function-definition function">dangle</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">-&gt;</span> <span class="token operator">&amp;</span><span class="token class-name">String</span> <span class="token punctuation">{</span>
  206. <span class="token keyword">let</span> s <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;Dangling reference&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  207. <span class="token operator">&amp;</span>s
  208. <span class="token punctuation">}</span>
  209. </code></pre></div><p>程序在 <code>dangle</code> 函数中声明了一个字符串,期望返回其的引用,但是函数结束后 s 便离开了他的作用域,即被销毁,因此返回的引用为空。这和 C 语言中返回局部变量的地址如出一辙,但是 Rust 在编译时就将避免这样的问题发生。</p> <p>报错:<code>missing lifetime specifier</code></p> <p><strong>引用的规则</strong></p> <p>在任何给定的时刻,只能满足下列条件之一:一个可变的引用,或者任意数量不可变的引用,而且引用必须一直有效。</p> <h2 id="六、切片"><a href="#六、切片" class="header-anchor">#</a> 六、切片</h2> <p>Rust 的另一种不持有所有权的数据类型:切片(Slice)</p> <p>下面编写这样一个函数进行示范:</p> <ul><li>它接收字符串作为参数</li> <li>返回它在这个字符串里找到的第一个单词</li> <li>如果函数没有找到任何空格,则返回整个字符串</li></ul> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  210. <span class="token keyword">let</span> <span class="token keyword">mut</span> s <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;Hello World&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  211. <span class="token keyword">let</span> space_index <span class="token operator">=</span> <span class="token function">first_word</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>s<span class="token punctuation">)</span><span class="token punctuation">;</span>
  212. s<span class="token punctuation">.</span><span class="token function">clear</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  213. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;The first blank's position is in {}.&quot;</span><span class="token punctuation">,</span> space_index<span class="token punctuation">)</span><span class="token punctuation">;</span>
  214. <span class="token punctuation">}</span>
  215. <span class="token keyword">fn</span> <span class="token function-definition function">first_word</span><span class="token punctuation">(</span>s<span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token class-name">String</span><span class="token punctuation">)</span> <span class="token punctuation">-&gt;</span> <span class="token keyword">usize</span> <span class="token punctuation">{</span>
  216. <span class="token keyword">let</span> bytes <span class="token operator">=</span> s<span class="token punctuation">.</span><span class="token function">as_bytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  217. <span class="token comment">/*
  218. byte 的 iter 方法会为数组 byte 创建一个迭代器,这个方法会依次返回集合中的每个元素
  219. enumerate 方法会将 iter 返回的结果进行包装,并把每个结果作为一个元组的一部分进行返回
  220. 元组的第一个元素就是遍历的索引,第二个元素就是数组中的元素(是一个引用),这里实际用到的是模式匹配
  221. 声明了两个变量对这个元组进行解构
  222. */</span>
  223. <span class="token keyword">for</span> <span class="token punctuation">(</span>i<span class="token punctuation">,</span> <span class="token operator">&amp;</span>item<span class="token punctuation">)</span> <span class="token keyword">in</span> bytes<span class="token punctuation">.</span><span class="token function">iter</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">enumerate</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  224. <span class="token keyword">if</span> item <span class="token operator">==</span> <span class="token char">b' '</span> <span class="token punctuation">{</span>
  225. <span class="token keyword">return</span> i<span class="token punctuation">;</span>
  226. <span class="token punctuation">}</span>
  227. <span class="token punctuation">}</span>
  228. s<span class="token punctuation">.</span><span class="token function">len</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  229. <span class="token punctuation">}</span>
  230. </code></pre></div><p>实际上这个函数的设计有一个缺陷,这个函数是将字符串空格的索引位置返回,而一旦这个结果脱离了这个字符串的上下文,这个返回值便没有了意义。换句话说,这个索引位置的结果是独立于字符串而存在的,在函数返回以后,我们就再也无法保证其有效性。举个例子,若函数获取 <code>Hello World</code> 这个字符串的空格位置,获取到函数返回值为 <code>5</code> 后,将该字符串清空 <code>s.clear()</code>,但是此时函数返回值 <code>space_index</code> 的值仍然是 <code>5</code>,这跟现在的字符串便没有了任何关联,因此这个返回值便没有了意义了。这样的 API 需要关注两者之间的同步性,但是往往都会比较繁琐。</p> <p>Rust 提供了切片类型用来解决这一问题。</p> <p><strong>字符串切片</strong></p> <p>字符串切片是指向字符串中一部分内容的引用</p> <p>形式:[开始索引..结束索引],前闭后开</p> <p><img src="https://raw.githubusercontent.com/CherryYang05/PicGo-image/master/images/20220513022342.png" alt="字符串切片"></p> <p>切片是放在 stack 上,右边的数组是放在 heap 上的。</p> <p><em>【更正】:s 切片的长度和容量应该为 11.</em></p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  231. <span class="token keyword">let</span> <span class="token keyword">mut</span> s <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;Hello World&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  232. <span class="token keyword">let</span> hello <span class="token operator">=</span> <span class="token operator">&amp;</span>s<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">..</span><span class="token number">5</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  233. <span class="token keyword">let</span> world <span class="token operator">=</span> <span class="token operator">&amp;</span>s<span class="token punctuation">[</span><span class="token number">6</span><span class="token punctuation">..</span><span class="token number">11</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  234. <span class="token punctuation">}</span>
  235. </code></pre></div><p>这里切片有三个语法糖,若切片的开始位置为 0,则可以省略写,若切片的末尾时字符串最后一个位置,即等于字符串长度,那么也可以省略不写,下面的例子和上面是等价的:</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  236. <span class="token keyword">let</span> <span class="token keyword">mut</span> s <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;Hello World&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  237. <span class="token keyword">let</span> hello <span class="token operator">=</span> <span class="token operator">&amp;</span>s<span class="token punctuation">[</span><span class="token punctuation">..</span><span class="token number">5</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  238. <span class="token keyword">let</span> world <span class="token operator">=</span> <span class="token operator">&amp;</span>s<span class="token punctuation">[</span><span class="token number">6</span><span class="token punctuation">..</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  239. <span class="token keyword">let</span> whole <span class="token operator">=</span> <span class="token operator">&amp;</span>s<span class="token punctuation">[</span><span class="token punctuation">..</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  240. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{}, {}&quot;</span><span class="token punctuation">,</span> hello<span class="token punctuation">,</span> world<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//输出为 Hello, World</span>
  241. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{}&quot;</span><span class="token punctuation">,</span> whole<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//输出为 Hello World</span>
  242. <span class="token punctuation">}</span>
  243. </code></pre></div><p><strong>注意:</strong></p> <ul><li><p>字符串切片的范围索引必须发生在有效的 <code>UTF-8</code> 字符边界内。</p></li> <li><p>如果尝试从一个多字节的字符中创建字符串切片,程序会报错并退出</p></li></ul> <p>下面用切片重写上面的函数:</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  244. <span class="token keyword">let</span> <span class="token keyword">mut</span> s <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">from</span><span class="token punctuation">(</span><span class="token string">&quot;Hello World&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  245. <span class="token keyword">let</span> space_index_slice <span class="token operator">=</span> <span class="token function">first_word_slice</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>s<span class="token punctuation">)</span><span class="token punctuation">;</span>
  246. s<span class="token punctuation">.</span><span class="token function">clear</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//报错</span>
  247. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;The first world is {}.&quot;</span><span class="token punctuation">,</span> space_index_slice<span class="token punctuation">)</span><span class="token punctuation">;</span>
  248. <span class="token punctuation">}</span>
  249. <span class="token keyword">fn</span> <span class="token function-definition function">first_word_slice</span><span class="token punctuation">(</span>s<span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token class-name">String</span><span class="token punctuation">)</span> <span class="token punctuation">-&gt;</span> <span class="token operator">&amp;</span><span class="token keyword">str</span> <span class="token punctuation">{</span>
  250. <span class="token keyword">let</span> bytes <span class="token operator">=</span> s<span class="token punctuation">.</span><span class="token function">as_bytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  251. <span class="token keyword">for</span> <span class="token punctuation">(</span>i<span class="token punctuation">,</span> <span class="token operator">&amp;</span>item<span class="token punctuation">)</span> <span class="token keyword">in</span> bytes<span class="token punctuation">.</span><span class="token function">iter</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">enumerate</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  252. <span class="token keyword">if</span> item <span class="token operator">==</span> <span class="token char">b' '</span> <span class="token punctuation">{</span>
  253. <span class="token keyword">return</span> <span class="token operator">&amp;</span>s<span class="token punctuation">[</span><span class="token punctuation">..</span>i<span class="token punctuation">]</span><span class="token punctuation">;</span>
  254. <span class="token punctuation">}</span>
  255. <span class="token punctuation">}</span>
  256. <span class="token operator">&amp;</span>s<span class="token punctuation">[</span><span class="token punctuation">..</span><span class="token punctuation">]</span>
  257. <span class="token punctuation">}</span>
  258. </code></pre></div><p>这里函数返回 <code>&amp;str</code> 表示字符串切片,若找到空格,将返回该位置之前的字符串切片,否则返回整个字符串切片。</p> <p>但是上述代码中 <code>s.clear()</code> 会报错,报错信息为:</p> <div class="language-rust extra-class"><pre class="language-rust"><code>error<span class="token punctuation">[</span><span class="token constant">E0502</span><span class="token punctuation">]</span><span class="token punctuation">:</span> cannot borrow `s` <span class="token keyword">as</span> mutable because it is also borrowed <span class="token keyword">as</span> immutable
  259. <span class="token operator">-</span><span class="token punctuation">-&gt;</span> src<span class="token operator">/</span>main<span class="token punctuation">.</span>rs<span class="token punctuation">:</span><span class="token number">7</span><span class="token punctuation">:</span><span class="token number">5</span>
  260. <span class="token operator">|</span>
  261. <span class="token number">5</span> <span class="token operator">|</span> <span class="token keyword">let</span> space_index_slice <span class="token operator">=</span> <span class="token function">first_word_slice</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>s<span class="token punctuation">)</span><span class="token punctuation">;</span>
  262. <span class="token operator">|</span> <span class="token operator">-</span><span class="token operator">-</span> immutable borrow occurs here
  263. <span class="token number">6</span> <span class="token operator">|</span>
  264. <span class="token number">7</span> <span class="token operator">|</span> s<span class="token punctuation">.</span><span class="token function">clear</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  265. <span class="token operator">|</span> <span class="token operator">^</span><span class="token operator">^</span><span class="token operator">^</span><span class="token operator">^</span><span class="token operator">^</span><span class="token operator">^</span><span class="token operator">^</span><span class="token operator">^</span><span class="token operator">^</span> mutable borrow occurs here
  266. <span class="token punctuation">...</span>
  267. <span class="token number">13</span> <span class="token operator">|</span> <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;The first blank's position is in {}.&quot;</span><span class="token punctuation">,</span> space_index_slice<span class="token punctuation">)</span><span class="token punctuation">;</span>
  268. <span class="token operator">|</span> <span class="token operator">-</span><span class="token operator">-</span><span class="token operator">-</span><span class="token operator">-</span><span class="token operator">-</span><span class="token operator">-</span><span class="token operator">-</span><span class="token operator">-</span><span class="token operator">-</span><span class="token operator">-</span><span class="token operator">-</span><span class="token operator">-</span><span class="token operator">-</span><span class="token operator">-</span><span class="token operator">-</span><span class="token operator">-</span><span class="token operator">-</span> immutable borrow later used here
  269. <span class="token class-name">For</span> more information about this error<span class="token punctuation">,</span> <span class="token keyword">try</span> `rustc <span class="token operator">-</span><span class="token operator">-</span>explain <span class="token constant">E0502</span>`<span class="token punctuation">.</span>
  270. error<span class="token punctuation">:</span> could not compile `slice` due to previous error
  271. </code></pre></div><p>即不能将变量 s 借用为可变,因为它已经被借用为不可变。在函数参数中用了不可变引用,但是下面 <code>s.clear()</code> 又要修改字符串的值,使其变成可变,这样便会报错。</p> <p><strong>字符串字面值是切片</strong></p> <ul><li>字符串字面值被直接存储在二进制程序中</li> <li><code>let s = &quot;Hello, World!&quot;;</code></li> <li>变量 s 的类型是 <code>&amp;str</code>,它是一个指向二进制程序特定位置的切片</li> <li><code>&amp;str</code> 是不可变引用,所以字符串字面值也是不可变的</li></ul> <p><strong>将字符串切片作为参数传递</strong></p> <p>有经验的 Rust 开发者会采用 <code>&amp;str</code> 作为参数类型,因为这样就可以同时接收 <code>String</code> 和 <code>&amp;str</code> 类型的参数了</p> <ul><li>使用字符串切片,直接调用该函数</li> <li>使用 <code>String</code>,可以创建一个完整的 <code>String</code> 切片来调用该函数</li> <li>定义函数时使用字符串切片来代替字符串引用会使我们的 API 更加通用,且不会损失任何功能</li></ul> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">first_word</span><span class="token punctuation">(</span>s<span class="token punctuation">:</span> <span class="token operator">&amp;</span><span class="token keyword">str</span><span class="token punctuation">)</span> <span class="token punctuation">-&gt;</span> <span class="token operator">&amp;</span><span class="token keyword">str</span> <span class="token punctuation">{</span>
  272. <span class="token comment">//TODO</span>
  273. <span class="token punctuation">}</span>
  274. </code></pre></div><p><strong>其他类型的切片</strong></p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  275. <span class="token keyword">let</span> a <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  276. <span class="token keyword">let</span> slice <span class="token operator">=</span> <span class="token operator">&amp;</span>a<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">..</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  277. <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">&quot;{}&quot;</span><span class="token punctuation">,</span> slice<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  278. <span class="token punctuation">}</span>
  279. </code></pre></div><p>这个切片类型为 <code>&amp;[i32]</code>,它存储了一个指向起始元素的位置的指针,还存储了一个长度,该例中为 <code>2</code></p></div> <footer class="page-edit"><!----> <!----></footer> <!----> </main></div><div class="global-ui"></div></div>
  280. <script src="/rust_camp_tutorial/assets/js/app.d7ab8f65.js" defer></script><script src="/rust_camp_tutorial/assets/js/2.3dc1b8de.js" defer></script><script src="/rust_camp_tutorial/assets/js/1.7f771cfb.js" defer></script><script src="/rust_camp_tutorial/assets/js/24.2f88b37d.js" defer></script>
  281. </body>
  282. </html>