123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236 |
- <!DOCTYPE html>
- <html lang="en-US">
- <head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width,initial-scale=1">
- <title>Rust 入门教程(四):常用的集合 | Rust训练营教程文档</title>
- <meta name="generator" content="VuePress 1.9.10">
- <link rel="icon" href="/rust_camp_tutorial/logo.png">
- <meta name="description" content="DragonOS-Rust camp">
-
- <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/32.30c1ff3b.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/24.2f88b37d.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/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">
- <link rel="stylesheet" href="/rust_camp_tutorial/assets/css/0.styles.7dd9be3e.css">
- </head>
- <body>
- <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">
- 首页
- </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">
- 首页
- </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%E5%9B%9B%EF%BC%89.html#_1-vector" class="sidebar-link">1. Vector</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%E5%9B%9B%EF%BC%89.html#_2-string" class="sidebar-link">2. String</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%E5%9B%9B%EF%BC%89.html#_2-1-字符串的创建" class="sidebar-link">2.1 字符串的创建</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%E5%9B%9B%EF%BC%89.html#_2-2-字符串更新" class="sidebar-link">2.2 字符串更新</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%E5%9B%9B%EF%BC%89.html#_2-3-字符串的索引" class="sidebar-link">2.3 字符串的索引</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%E5%9B%9B%EF%BC%89.html#_2-4-切割-string" class="sidebar-link">2.4 切割 String</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%E5%9B%9B%EF%BC%89.html#_2-5-遍历-string" class="sidebar-link">2.5 遍历 String</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%E5%9B%9B%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%E5%9B%9B%EF%BC%89.html#_3-hashmap" class="sidebar-link">3. HashMap</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%E5%9B%9B%EF%BC%89.html#_3-1-创建-hashmap" class="sidebar-link">3.1 创建 HashMap</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%E5%9B%9B%EF%BC%89.html#_3-2-访问-hashmap" class="sidebar-link">3.2 访问 HashMap</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%E5%9B%9B%EF%BC%89.html#_3-3-遍历-hashmap" class="sidebar-link">3.3 遍历 HashMap</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%E5%9B%9B%EF%BC%89.html#_3-4-更新-hashmap" class="sidebar-link">3.4 更新 HashMap</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%E5%9B%9B%EF%BC%89.html#_3-5-hash-函数" class="sidebar-link">3.5 Hash 函数</a></li></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> <blockquote><p>这一节介绍 Rust 中常用的几种集合类型:<code>Vector</code>,<code>String</code> 和 <code>HashMap</code>,这些集合类型都是存储在 Heap 中,不需要编译时确定大小,可以在运行时动态改变大小。</p></blockquote> <h2 id="_1-vector"><a href="#_1-vector" class="header-anchor">#</a> 1. Vector</h2> <p>Vector 概念略,和 C++ STL 中的 Vector 差不多,下面来看使用:</p> <p><strong>创建 Vector</strong></p> <p>使用 <code>Vec::new()</code> 函数创建一个空 Vector,<code>let v: Vec<i32> = Vec::new();</code>(注意 V 是大写),也可以设定初始值进行创建,这时就要使用 <code>vec!</code> 宏,注意这里 v 是小写,<code>let v: vec![1, 2, 3];</code>。</p> <p><strong>更新 Vector</strong></p> <p>使用 <code>push</code> 方法向 vector 里添加元素</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>
- <span class="token keyword">let</span> <span class="token keyword">mut</span> vec <span class="token operator">=</span> <span class="token class-name">Vec</span><span class="token punctuation">::</span><span class="token function">new</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- vec<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- vec<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- vec<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- vec<span class="token punctuation">.</span><span class="token function">push</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 punctuation">}</span>
- </code></pre></div><p>使用 <code>Vec::new()</code> 创建 vector 时,需要显式指明类型,但是若下面用 push 函数添加 vector 元素时,编译器可以根据上下文推断出类型,于是便可以不用显式指定类型了。</p> <p><strong>删除 Vector</strong></p> <p>与任何其它 struct 一样,当 Vector 离开作用域后,它就被清理掉了,同时它所有的元素也被清理掉了</p> <p><strong>读取 Vector 元素</strong></p> <ul><li>索引</li> <li>get 方法</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">test01</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <span class="token keyword">let</span> v <span class="token operator">=</span> <span class="token macro property">vec!</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">38</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">45</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
- <span class="token keyword">let</span> third <span class="token operator">=</span> <span class="token operator">&</span>v<span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
- <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"The third element is {}."</span><span class="token punctuation">,</span> third<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token keyword">match</span> v<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <span class="token class-name">Some</span><span class="token punctuation">(</span>third<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"The third element is {}."</span><span class="token punctuation">,</span> third<span class="token punctuation">)</span><span class="token punctuation">,</span>
- <span class="token class-name">None</span> <span class="token operator">=></span> <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"There is no element in the vec."</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
- <span class="token punctuation">}</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>因为 Vector 的 get 方法返回一个 Option 枚举类型,因此用 Some 和 None 做模式匹配。</p> <p>但是如果用索引访问的下标越界的话,就会发生 panic,<strong>但是使用 get 的话,会返回 None.</strong></p> <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">test02</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <span class="token keyword">let</span> v <span class="token operator">=</span> <span class="token macro property">vec!</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">12</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>
- <span class="token keyword">let</span> first <span class="token operator">=</span> <span class="token operator">&</span>v<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
- v<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"{}"</span><span class="token punctuation">,</span> first<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>上面这段代码在 <code>v.push();</code> 会报错,原因是 <code>first</code> 已经借用 v 为不可变引用,而 push 操作又将 v 变成可变的,因此会报错。</p> <p>vector 之所以也有所有权和借用规则这样的机制,是因为 vector 是存储在堆中,并且数据是连续存放,如果在后面添加一个元素,而原来的内存中后面没有多余空间,则编译器将会在内存中重新寻找一块更大的内存来存放新的 vector,所以这是还是用原来 vector 的引用,就会发生错误。</p> <p>实际上 C++ 中的 vector 也是这样的,但是 Rust 的语言机制从编译时就避免了,而不用等到运行时在发现错了,这也体现了 Rust 的高安全性和可靠性。下面是 C++ 中的 vector 元素首地址改变的例子,<a href="https://blog.csdn.net/wch0lalala/article/details/108337051" target="_blank" rel="noopener noreferrer">参考博客<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></p> <div class="language-cpp extra-class"><pre class="language-cpp"><code><span class="token macro property"><span class="token directive-hash">#</span><span class="token directive keyword">include</span> <span class="token string"><iostream></span></span>
- <span class="token macro property"><span class="token directive-hash">#</span><span class="token directive keyword">include</span> <span class="token string"><vector></span></span>
- <span class="token keyword">using</span> <span class="token keyword">namespace</span> std<span class="token punctuation">;</span>
- <span class="token keyword">int</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
- vector<span class="token operator"><</span><span class="token keyword">int</span><span class="token operator">></span> arr<span class="token punctuation">;</span>
- arr<span class="token punctuation">.</span><span class="token function">push_back</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- cout <span class="token operator"><<</span> <span class="token string">"arr's size :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> <span class="token string">" capacity :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">capacity</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> <span class="token string">" head address :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">data</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> endl<span class="token punctuation">;</span>
- arr<span class="token punctuation">.</span><span class="token function">push_back</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- cout <span class="token operator"><<</span> <span class="token string">"arr's size :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> <span class="token string">" capacity :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">capacity</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> <span class="token string">" head address :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">data</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> endl<span class="token punctuation">;</span>
- arr<span class="token punctuation">.</span><span class="token function">push_back</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- cout <span class="token operator"><<</span> <span class="token string">"arr's size :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> <span class="token string">" capacity :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">capacity</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> <span class="token string">" head address :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">data</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> endl<span class="token punctuation">;</span>
- arr<span class="token punctuation">.</span><span class="token function">push_back</span><span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- cout <span class="token operator"><<</span> <span class="token string">"arr's size :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> <span class="token string">" capacity :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">capacity</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> <span class="token string">" head address :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">data</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> endl<span class="token punctuation">;</span>
- arr<span class="token punctuation">.</span><span class="token function">push_back</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- cout <span class="token operator"><<</span> <span class="token string">"arr's size :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> <span class="token string">" capacity :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">capacity</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> <span class="token string">" head address :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">data</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> endl<span class="token punctuation">;</span>
- arr<span class="token punctuation">.</span><span class="token function">push_back</span><span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- cout <span class="token operator"><<</span> <span class="token string">"arr's size :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> <span class="token string">" capacity :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">capacity</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> <span class="token string">" head address :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">data</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> endl<span class="token punctuation">;</span>
- arr<span class="token punctuation">.</span><span class="token function">push_back</span><span class="token punctuation">(</span><span class="token number">7</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- cout <span class="token operator"><<</span> <span class="token string">"arr's size :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> <span class="token string">" capacity :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">capacity</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> <span class="token string">" head address :"</span> <span class="token operator"><<</span> arr<span class="token punctuation">.</span><span class="token function">data</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator"><<</span> endl<span class="token punctuation">;</span>
- <span class="token keyword">return</span> <span class="token number">0</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>输出结果为:</p> <div class="language-cpp extra-class"><pre class="language-cpp"><code>arr<span class="token number">'</span>s size <span class="token operator">:</span><span class="token number">1</span> capacity <span class="token operator">:</span><span class="token number">1</span> head address <span class="token operator">:</span><span class="token number">0x10516fb0</span>
- arr<span class="token number">'</span>s size <span class="token operator">:</span><span class="token number">2</span> capacity <span class="token operator">:</span><span class="token number">2</span> head address <span class="token operator">:</span><span class="token number">0x10516e30</span>
- arr<span class="token number">'</span>s size <span class="token operator">:</span><span class="token number">3</span> capacity <span class="token operator">:</span><span class="token number">4</span> head address <span class="token operator">:</span><span class="token number">0x10516fb0</span>
- arr<span class="token number">'</span>s size <span class="token operator">:</span><span class="token number">4</span> capacity <span class="token operator">:</span><span class="token number">4</span> head address <span class="token operator">:</span><span class="token number">0x10516fb0</span>
- arr<span class="token number">'</span>s size <span class="token operator">:</span><span class="token number">5</span> capacity <span class="token operator">:</span><span class="token number">8</span> head address <span class="token operator">:</span><span class="token number">0x10516e30</span>
- arr<span class="token number">'</span>s size <span class="token operator">:</span><span class="token number">6</span> capacity <span class="token operator">:</span><span class="token number">8</span> head address <span class="token operator">:</span><span class="token number">0x10516e30</span>
- arr<span class="token number">'</span>s size <span class="token operator">:</span><span class="token number">7</span> capacity <span class="token operator">:</span><span class="token number">8</span> head address <span class="token operator">:</span><span class="token number">0x10516e30</span>
- </code></pre></div><p>我们发现每次 vector 扩容时元素首地址都会改变。(注意在 vector 中,&vec 和 &vec[0] 是不一样的,这是因为 vector 结构存在栈中,而 vector 的数据存在堆中,&vec 获得的只是栈中 vec 的结构的地址,始终不变,而 &vec[0] 是堆中 vector 存储的真正的元素地址,每次动态扩容后都会改变)</p> <p>好我们回到 Rust。</p> <p><strong>遍历 vector</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">test03</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <span class="token keyword">let</span> v <span class="token operator">=</span> <span class="token macro property">vec!</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 punctuation">;</span>
- <span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token operator">&</span>v <span class="token punctuation">{</span>
- <span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"{}"</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- <span class="token punctuation">}</span>
- </code></pre></div><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>
- <span class="token keyword">let</span> <span class="token keyword">mut</span> <span class="token macro property">vec!</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 punctuation">;</span>
- <span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token operator">&</span><span class="token keyword">mut</span> v <span class="token punctuation">{</span>
- <span class="token operator">*</span>i <span class="token operator">+=</span> <span class="token number">5</span><span class="token punctuation">;</span>
- <span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"{}"</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>这里 <code>*i</code> 是解引用,我们以后会介绍。</p> <p><strong>使用 enum 来存储多种数据类型</strong></p> <p>vector 只能存储一种数据类型,但是我们有时候想存储不同类型的数据,我们可以用可附加数据的枚举来创建 vector。</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">enum</span> <span class="token type-definition class-name">Spreadsheetcell</span> <span class="token punctuation">{</span>
- <span class="token class-name">Int</span><span class="token punctuation">(</span><span class="token keyword">i32</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
- <span class="token class-name">Float</span><span class="token punctuation">(</span><span class="token keyword">f64</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
- <span class="token class-name">Text</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
- <span class="token punctuation">}</span>
- <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>
- <span class="token keyword">let</span> v <span class="token operator">=</span> <span class="token macro property">vec!</span><span class="token punctuation">[</span>
- <span class="token class-name">Spreadsheetcell</span><span class="token punctuation">::</span><span class="token class-name">Int</span><span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
- <span class="token class-name">Spreadsheetcell</span><span class="token punctuation">::</span><span class="token class-name">Text</span><span class="token punctuation">(</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">"Computer Science"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
- <span class="token class-name">Spreadsheetcell</span><span class="token punctuation">::</span><span class="token class-name">Float</span><span class="token punctuation">(</span><span class="token number">6.18</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
- <span class="token punctuation">]</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>使用枚举的变体就可以在 vector 中存储不同类型的数据了。</p> <h2 id="_2-string"><a href="#_2-string" class="header-anchor">#</a> 2. String</h2> <p>String 这个数据类型是所有编程语言中都非常重要的一个类型,Rust 开发者经常会被字符串困扰的原因是,Rust 倾向于暴露可能的错误,而且字符串数据结构复杂并且采用了 UTF-8 编码。</p> <p><a href="#%E5%90%84%E7%A7%8D%E7%B1%BB%E5%9E%8B%E7%9A%84%E7%BC%96%E7%A0%81">编码类型和编码方式</a></p> <p>在 Rust 中,字符串是 Byte 的集合,并且有一些方法将 byte 解析为文本。</p> <p><strong>字符串是什么</strong></p> <p>从 Rust 语言的核心层面上将,只有一个字符串类型,叫字符串切片 <code>str</code>,它通常以引用的形式出现(即 <code>&str</code>)。</p> <p>字符串切片是对存储在其他地方,用 UTF-8 编码的字符串的引用。<strong>字符串字面值:存储在二进制文件中,也是字符串切片</strong></p> <p><strong>String 类型,来自标准库,而不是核心语言</strong>,他可增长、可修改、可拥有,采用 UTF-8 编码,我们通常所说的字符串是指 <code>String</code> 和 <code>&str</code> 两者,而不是单指某一种。当然这里主要将的是 <code>String</code>。</p> <p><strong>其它类型的字符串</strong></p> <p>Rust 的标准库还包含了很多其它的字符串类型,例如:OsString,OsStr、CString、CStr</p> <ul><li>String vs Str 后缀:拥有或借用的变体</li> <li>可存储不同编码的文本或在内存中以不同的形式展现</li> <li>Library crate 针对存储字符串可提供更多的选项</li></ul> <h3 id="_2-1-字符串的创建"><a href="#_2-1-字符串的创建" class="header-anchor">#</a> 2.1 字符串的创建</h3> <ul><li>很多 <code>Vec<T></code> 都可用于 <code>String</code></li> <li>利用 <code>String::new()</code> 创建字符串</li> <li>使用初始值来创建 String:
- <ul><li><code>to_string()</code> <strong>方法</strong>,可用于实现了 Display trait 的类型,包括字符串字面值</li> <li><code>String::from()</code> <strong>函数</strong>,从字面值创建 String 类型</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">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <span class="token keyword">let</span> <span class="token keyword">mut</span> s1 <span class="token operator">=</span> <span class="token class-name">String</span><span class="token punctuation">::</span><span class="token function">new</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token keyword">let</span> <span class="token keyword">mut</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">"Hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token keyword">let</span> <span class="token keyword">mut</span> s3 <span class="token operator">=</span> <span class="token string">"Hello, Rust"</span><span class="token punctuation">;</span>
- <span class="token keyword">let</span> <span class="token keyword">mut</span> s4 <span class="token operator">=</span> <span class="token string">"Hello, Rust"</span><span class="token punctuation">.</span><span class="token function">to_string</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>通过字符串字面值创建的 <code>s3</code> 是切片类型,其他都是 String 类型</p> <p>【注】:我理解的函数就是没有 self 参数的,通过 <code>::</code> 来调用,而方法则是带有 <code>&self</code> 为其第一个参数,是通过实例来调用的,使用的是点调用的方式</p> <h3 id="_2-2-字符串更新"><a href="#_2-2-字符串更新" class="header-anchor">#</a> 2.2 字符串更新</h3> <ul><li>使用 <code>push_str()</code> <strong>方法</strong>,把一个字符串切片附加到 String,这个方法不会获得参数的所有权</li> <li>使用 <code>push()</code> <strong>方法</strong>,将一个单独的字符附加到 String 后</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>
- <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">"Hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</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">", Rust"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- s<span class="token punctuation">.</span><span class="token function">push_str</span><span class="token punctuation">(</span><span class="token operator">&</span>s1<span class="token punctuation">)</span><span class="token punctuation">;</span>
- s1<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span><span class="token char">'x'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"{}"</span><span class="token punctuation">,</span> s1<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>这里还是可以打印出 s1 的值,说明没有获得 s1 的所有权。</p> <ul><li><code>+</code> 用来连接字符串,注意加号前是<strong>字符串类型</strong>,后面是<strong>字符串类型的引用</strong> <ul><li>使用了类似这个签名的方法 <code>fn add(self, s: &str) -> String { ... }</code></li> <li>标准库中 <code>add</code> 方法使用了泛型</li> <li>解引用强制转换(deref coercion)</li> <li>只能把 <code>&str</code> 添加到 <code>String</code></li></ul></li> <li><code>format!</code> 用于连接多个字符串</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">test03</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</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">"Hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <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">", Rust"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token keyword">let</span> s3 <span class="token operator">=</span> s1 <span class="token operator">+</span> <span class="token operator">&</span>s2<span class="token punctuation">;</span>
- <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"{}"</span><span class="token punctuation">,</span> s3<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"{}"</span><span class="token punctuation">,</span> s1<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"{}"</span><span class="token punctuation">,</span> s2<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>上述例子中,我们发现 <code>s1</code> 不能再使用了,而 <code>s2</code> 可以再被使用,因为底层方法中使用了类似这个签名的方法 <code>fn add(self, s: &str) -> String { ... }</code>,是将字符串自身和另一个字符串的切片进行相加组合。但是 <code>s2</code> 是字符串类型,而函数参数中是字符串切片类型,不匹配,为什么代码 <code>let s3 = s1 + &s2;</code> 能够编译通过?</p> <p>这是因为标准库中 <code>add</code> 方法使用了泛型,Rust 采用了一种叫 <strong>解引用强制转换(deref coercion)</strong> 的技术,强制将字符串类型转化成字符串切片类型,因此 <code>s2</code> 的所有权就会被保留,而 <code>add</code> 函数就会取得第一个参数的所有权,当函数调用完毕时,<code>s1</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">test04</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</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">"tic"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <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">"tac"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token keyword">let</span> s3 <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">"toc"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token comment">// let s3 = s1 + "-" + &s2 + "-" + &s3;</span>
- <span class="token comment">// println!("{}", s3);</span>
- <span class="token keyword">let</span> res <span class="token operator">=</span> <span class="token macro property">format!</span><span class="token punctuation">(</span><span class="token string">"{}-{}-{}"</span><span class="token punctuation">,</span> s1<span class="token punctuation">,</span> s2<span class="token punctuation">,</span> s3<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"{}"</span><span class="token punctuation">,</span> res<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>上述例子中将三个字符串之间用 <code>-</code> 连接,如果代码太多显得很繁琐,采用 <code>format!</code> 宏不仅可以使得代码简单易读,更重要的是不会取得所有变量的所有权。这个宏和 <code>println!</code> 很像,只不过 <code>format!</code> 宏是将结果返回,这里可以用一个变量去接收。</p> <h3 id="_2-3-字符串的索引"><a href="#_2-3-字符串的索引" class="header-anchor">#</a> 2.3 字符串的索引</h3> <p>不可以按照索引的语法对 String 某部分进行访问,因为 String 类型没有实现 <code>Index<Integer></code> trait,例如:</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">fn</span> <span class="token function-definition function">test</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <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">"Hello"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token keyword">let</span> s1 <span class="token operator">=</span> s<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">;</span> <span class="token comment">//这样是错误的</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>之所以无法通过索引进行访问是因为,字符串是用 UTF-8 进行编码,每一个字符都对应一个 Unicode 编码。在英文中,一个字符是 <code>1B</code>,而对于某些语言,一个字符可能对应 <code>2B</code>,而中文一个字符对应 <code>3B</code>,因此用索引进行访问的话,无法知道应该取一个字节还是两个字节。</p> <p>当然 Rust 不允许通过索引进行访问的另一个原因是,索引操作理应只消耗 <code>O(1)</code> 的时间,但是为了保证不会越界,需要使用 <code>O(n)</code> 的时间进行遍历字符串长度。</p> <p><strong>String 内部表示</strong></p> <p>String 实际上是对 <code>Vec<u8></code> 进行的包装,可以用 <code>len()</code> 方法获得字符串长度</p> <p>字节(Bytes),标量值(Scalar Values),字形簇(Grapheme Clusters)</p> <p>Rust有三种看待字符串的方式:</p> <ul><li>字节</li> <li>标量值</li> <li>字形簇(最接近所谓的“字母”)</li></ul> <h3 id="_2-4-切割-string"><a href="#_2-4-切割-string" class="header-anchor">#</a> 2.4 切割 String</h3> <p>可以使用 <code>[]</code> 和 <code>一个范围</code> 来创建一个字符串的切片</p> <ul><li>要谨慎使用</li> <li>如果切割时越过边界就会 panic</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">test05</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <span class="token keyword">let</span> hello <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">"你好吗"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token keyword">let</span> s <span class="token operator">=</span> <span class="token operator">&</span>hello<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">..</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
- <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"{}"</span><span class="token punctuation">,</span> s<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>上面我们说了在 Rust 中一个中文字符占 <code>3B</code>,因此我们获取字符串 hello 的前 3 个字节,输出结果为 <code>你</code>,但是要注意的是,所获取的字节必须能够构成所定义的字符,比如只获取前两字节最后运行就会报错(但是编译不会报错)。</p> <h3 id="_2-5-遍历-string"><a href="#_2-5-遍历-string" class="header-anchor">#</a> 2.5 遍历 String</h3> <ul><li>对于标量值:chars() 方法</li> <li>对于字节:bytes() 方法</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">test05</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <span class="token keyword">let</span> hello <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">"你好吗"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token keyword">for</span> i <span class="token keyword">in</span> hello<span class="token punctuation">.</span><span class="token function">chars</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <span class="token macro property">print!</span><span class="token punctuation">(</span><span class="token string">"{} "</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token keyword">for</span> i <span class="token keyword">in</span> hello<span class="token punctuation">.</span><span class="token function">bytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <span class="token macro property">print!</span><span class="token punctuation">(</span><span class="token string">"{} "</span><span class="token punctuation">,</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>最后输出结果为:</p> <div class="language-rust extra-class"><pre class="language-rust"><code>你 好 吗
- <span class="token number">228</span> <span class="token number">189</span> <span class="token number">160</span> <span class="token number">229</span> <span class="token number">165</span> <span class="token number">189</span> <span class="token number">229</span> <span class="token number">144</span> <span class="token number">151</span>
- </code></pre></div><p><strong>String不简单</strong></p> <ul><li>Rust 选择将正确处理 String 数据作为所有 Rust 程序的默认行为——程序员必须在处理 UTF-8 数据之前投入更多的精力</li> <li>可防止在开发后期处理涉及非 ASCII 字符的错误</li></ul> <h3 id="各种类型的编码"><a href="#各种类型的编码" class="header-anchor">#</a> 各种类型的编码</h3> <ul><li>1967 年 ASCII,包含英文字母,阿拉伯数字,西文字符和控制字符</li> <li>1980 年 GB2312,包含简体中文,拉丁字母和日文假名</li> <li>1984 年 BIG5,增加了繁体字</li> <li>1993 年 GB130001,包含了中日韩三国文字</li> <li>1995 年 GBK,不支持韩文</li> <li>2000 年 GB18030,兼容更多的字符</li></ul> <p>在 1994 年诞生的 Unicode 实现了编码的全球化。</p> <p>那么这时候如何表示字符呢,英文所需要表示的二进制位和汉字所要表示的二进制位肯定是不同的,也就是说一个英文字符可能要占 1B,而汉字要占 2B,编码时都是将二进制连接在一起,那么怎么知道当前的一个字节所要表示的是英文还是中文呢?因此直接将每个字符用编号表示无法正确区分每个字符的边界。</p> <p>一种解决方法是 <strong>定长编码</strong>,即每个字符都用统一长度表示,位数不够前面补 0。但是这样又出现了一个问题,一个英文字母要占两个字节,要忍受前面全是 0 的情况,只会占用更多的内存。</p> <p><img src="https://raw.githubusercontent.com/CherryYang05/PicGo-image/master/images/20220519005429.png" alt="定长编码"></p> <p>解决方法也很简单,可以采用 <strong>变长编码</strong>,那么如何区分字符边界呢?其实和计组中的 <strong>拓展操作码</strong>,<strong>IP 地址</strong>,<strong>哈夫曼编码</strong> 都很类似,如下图所示:</p> <p><img src="https://raw.githubusercontent.com/CherryYang05/PicGo-image/master/images/20220519005820.png" alt="变长编码"></p> <p>这就是 <strong>UTF-8 编码</strong></p> <h2 id="_3-hashmap"><a href="#_3-hashmap" class="header-anchor">#</a> 3. HashMap</h2> <p>和各种语言中的 HashMap 一样,也是通过键值对来存储数据,通过键(Key)来寻找数据,而不是索引</p> <h3 id="_3-1-创建-hashmap"><a href="#_3-1-创建-hashmap" class="header-anchor">#</a> 3.1 创建 HashMap</h3> <ul><li>创建空 HashMap:new() 函数</li> <li>添加数据:insert() 方法</li></ul> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token keyword">use</span> <span class="token namespace">std<span class="token punctuation">::</span>collections<span class="token punctuation">::</span></span><span class="token class-name">HashMap</span><span class="token punctuation">;</span>
- <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>
- <span class="token keyword">let</span> <span class="token keyword">mut</span> hash<span class="token punctuation">:</span> <span class="token class-name">HashMap</span><span class="token operator"><</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token keyword">i32</span><span class="token operator">></span> <span class="token operator">=</span> <span class="token class-name">HashMap</span><span class="token punctuation">::</span><span class="token function">new</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- hash<span class="token punctuation">.</span><span class="token function">insert</span><span class="token punctuation">(</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">"Cherry"</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">23</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>若声明的时候没有指定类型,则必须要插入数据才不会报错,若声明时已经指定类型了,那么不用插入数据也不会报错。</p> <ul><li>HashMap 用的较少,不在 Prelude中</li> <li>标准库对其支持较少,没有内置的宏来创建</li> <li>HashMap 数据存储在 heap 上</li> <li>同构的。一个 HashMap 中
- <ul><li>所有的 K 必须是同一种类型</li> <li>所有的 V 必须是同一种类型</li></ul></li></ul> <p><strong>另一种创建 HashMap 的方式:collect 方法</strong></p> <p>在元素类型为 Tuple 的 Vector 上使用 collect 方法,可以组建一个 HashMap</p> <ul><li>要求 Tuple 有两个值:一个作为 K,一个作为 V</li> <li>collect 方法可以把数据整合成很多种集合类型,包括 HashMap</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">test02</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <span class="token keyword">let</span> teams <span class="token operator">=</span> <span class="token macro property">vec!</span><span class="token punctuation">[</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">"Suns"</span><span class="token punctuation">)</span><span class="token punctuation">,</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">"Lakers"</span><span class="token punctuation">)</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
- <span class="token keyword">let</span> rank <span class="token operator">=</span> <span class="token macro property">vec!</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
- <span class="token keyword">let</span> nba<span class="token punctuation">:</span> <span class="token class-name">HashMap</span><span class="token operator"><</span>_<span class="token punctuation">,</span> _<span class="token operator">></span> <span class="token operator">=</span> teams<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">zip</span><span class="token punctuation">(</span>rank<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 punctuation">.</span><span class="token function">collect</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>使用 <code>collect</code> 时,要显式声明返回类型,因为它可以生成各种类型。</p> <p><strong>HashMap 和所有权</strong></p> <p>对于实现了 Copy trait 的类型(例如i32),值会被复制到 HashMap 中。对于拥有所有权的值(例如String),值会被移动,所有权会转移给 HashMap。</p> <p>如果将值的引用插入到 HashMap,值本身不会移动一在 HashMap 有效的期间,<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">test03</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <span class="token keyword">let</span> key <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">"Suns"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token keyword">let</span> value <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">"Champion"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token keyword">let</span> <span class="token keyword">mut</span> map <span class="token operator">=</span> <span class="token class-name">HashMap</span><span class="token punctuation">::</span><span class="token function">new</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- map<span class="token punctuation">.</span><span class="token function">insert</span><span class="token punctuation">(</span>key<span class="token punctuation">,</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"{} {}"</span><span class="token punctuation">,</span> key<span class="token punctuation">,</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//这里会报错,因为key和value所有权已经没有了</span>
- <span class="token comment">//通常应该是这样插入数据</span>
- map<span class="token punctuation">.</span><span class="token function">insert</span><span class="token punctuation">(</span><span class="token operator">&</span>key<span class="token punctuation">,</span> <span class="token operator">&</span>value<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>这里在堆 HashMap 赋值之后,key 和 value 的所有权就被转移给了 HashMap,通常都是传入字符串的引用。</p> <h3 id="_3-2-访问-hashmap"><a href="#_3-2-访问-hashmap" class="header-anchor">#</a> 3.2 访问 HashMap</h3> <p>get方法</p> <ul><li>参数:K</li> <li>返回:<code>Option<&V></code></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">test04</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <span class="token keyword">let</span> <span class="token keyword">mut</span> nba <span class="token operator">=</span> <span class="token class-name">HashMap</span><span class="token punctuation">::</span><span class="token function">new</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- nba<span class="token punctuation">.</span><span class="token function">insert</span><span class="token punctuation">(</span><span class="token string">"Suns"</span><span class="token punctuation">.</span><span class="token function">to_string</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- nba<span class="token punctuation">.</span><span class="token function">insert</span><span class="token punctuation">(</span><span class="token string">"Lakers"</span><span class="token punctuation">.</span><span class="token function">to_string</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token keyword">let</span> team <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">"Suns"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token keyword">let</span> rank <span class="token operator">=</span> nba<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token operator">&</span>team<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token keyword">match</span> rank <span class="token punctuation">{</span>
- <span class="token class-name">Some</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"{}"</span><span class="token punctuation">,</span> s<span class="token punctuation">)</span><span class="token punctuation">,</span>
- <span class="token class-name">None</span> <span class="token operator">=></span> <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"team not exist"</span><span class="token punctuation">)</span>
- <span class="token punctuation">}</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>HashMap 的 get 方法返回的是一个 Option 枚举,并且 get 方法的参数是 String 的引用。</p> <h3 id="_3-3-遍历-hashmap"><a href="#_3-3-遍历-hashmap" class="header-anchor">#</a> 3.3 遍历 HashMap</h3> <p>使用 for 循环:</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>
- <span class="token keyword">let</span> <span class="token keyword">mut</span> nba <span class="token operator">=</span> <span class="token class-name">HashMap</span><span class="token punctuation">::</span><span class="token function">new</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- nba<span class="token punctuation">.</span><span class="token function">insert</span><span class="token punctuation">(</span><span class="token string">"Suns"</span><span class="token punctuation">.</span><span class="token function">to_string</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- nba<span class="token punctuation">.</span><span class="token function">insert</span><span class="token punctuation">(</span><span class="token string">"Lakers"</span><span class="token punctuation">.</span><span class="token function">to_string</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token keyword">for</span> <span class="token punctuation">(</span>k<span class="token punctuation">,</span> v<span class="token punctuation">)</span> <span class="token keyword">in</span> <span class="token operator">&</span>nba <span class="token punctuation">{</span>
- <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"{}: {}"</span><span class="token punctuation">,</span> k<span class="token punctuation">,</span> v<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>(k, v) 这里是用元组做模式匹配。</p> <h3 id="_3-4-更新-hashmap"><a href="#_3-4-更新-hashmap" class="header-anchor">#</a> 3.4 更新 HashMap</h3> <ul><li>HashMap 大小可变</li> <li>每个 K 同时只能对应一个 V</li> <li>更新 HashMap 中的数据</li> <li>K 已经存在,对应一个 V
- <ul><li>替换现有的 V</li> <li>保留现有的 V,忽略新的 V</li> <li>合并现有的 V 和新的 V</li></ul></li> <li>K 不存在
- <ul><li>添加一对新的 K, V</li></ul></li></ul> <p><strong>替换现有的 V</strong></p> <p>如果向 HashMap 插入一对 (K, V),然后再插入同样的 K,但是不同的 V,那么原来的 V 会被替换掉</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>
- <span class="token keyword">let</span> <span class="token keyword">mut</span> scores <span class="token operator">=</span> <span class="token class-name">HashMap</span><span class="token punctuation">::</span><span class="token function">new</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- scores<span class="token punctuation">.</span><span class="token function">insert</span><span class="token punctuation">(</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">"Suns"</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">115</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- scores<span class="token punctuation">.</span><span class="token function">insert</span><span class="token punctuation">(</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">"Suns"</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">132</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//覆盖</span>
- <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"{:?}"</span><span class="token punctuation">,</span> scores<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p><strong>只在 K 不对应任何值的情况下,才插入 V</strong></p> <p>entry方法</p> <ul><li>检查指定的 K 是否对应一个 V</li> <li>参数为 K</li> <li>返回 enum Entry:代表值是否存在</li></ul> <p>Entry 的 or_insert()方法</p> <ul><li>返回
- <ul><li>如果 K 存在,返回到对应的 V 的一个可变引用</li> <li>如果 K 不存在,将方法参数作为 K 的新值插进去,返回到这个值的可变引用</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">test05</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <span class="token keyword">let</span> <span class="token keyword">mut</span> scores <span class="token operator">=</span> <span class="token class-name">HashMap</span><span class="token punctuation">::</span><span class="token function">new</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- scores<span class="token punctuation">.</span><span class="token function">insert</span><span class="token punctuation">(</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">"Suns"</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">115</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- scores<span class="token punctuation">.</span><span class="token function">entry</span><span class="token punctuation">(</span><span class="token string">"Lakers"</span><span class="token punctuation">.</span><span class="token function">to_string</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">or_insert</span><span class="token punctuation">(</span><span class="token number">90</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"{:?}"</span><span class="token punctuation">,</span> scores<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>这里 <code>scores.entry()</code> 返回 Entry,如果没有值的话,会返回类似于 <code>Entry(VacantEntry("Lakers"))</code> 的枚举。</p> <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">test06</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <span class="token keyword">let</span> text <span class="token operator">=</span> <span class="token string">"What a wonderful world a a a"</span><span class="token punctuation">;</span>
- <span class="token keyword">let</span> <span class="token keyword">mut</span> map <span class="token operator">=</span> <span class="token class-name">HashMap</span><span class="token punctuation">::</span><span class="token function">new</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token keyword">for</span> word <span class="token keyword">in</span> text<span class="token punctuation">.</span><span class="token function">split_whitespace</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
- <span class="token keyword">let</span> count <span class="token operator">=</span> map<span class="token punctuation">.</span><span class="token function">entry</span><span class="token punctuation">(</span>word<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">or_insert</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token operator">*</span>count <span class="token operator">+=</span> <span class="token number">1</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- <span class="token macro property">println!</span><span class="token punctuation">(</span><span class="token string">"{:#?}"</span><span class="token punctuation">,</span> map<span class="token punctuation">)</span><span class="token punctuation">;</span>
- <span class="token punctuation">}</span>
- </code></pre></div><p>最终返回结果为:</p> <div class="language-rust extra-class"><pre class="language-rust"><code><span class="token punctuation">{</span>
- <span class="token string">"wonderful"</span><span class="token punctuation">:</span> <span class="token number">1</span><span class="token punctuation">,</span>
- <span class="token string">"world"</span><span class="token punctuation">:</span> <span class="token number">1</span><span class="token punctuation">,</span>
- <span class="token string">"a"</span><span class="token punctuation">:</span> <span class="token number">4</span><span class="token punctuation">,</span>
- <span class="token string">"What"</span><span class="token punctuation">:</span> <span class="token number">1</span><span class="token punctuation">,</span>
- <span class="token punctuation">}</span>
- </code></pre></div><h3 id="_3-5-hash-函数"><a href="#_3-5-hash-函数" class="header-anchor">#</a> 3.5 Hash 函数</h3> <p>默认情况下,HashMap 使用加密功能强大的 Hash 函数,可以抵抗拒绝服务(DoS)攻击。</p> <ul><li>不是可用的最快的 Hash 算法</li> <li>但具有更好安全性。</li> <li>可以指定不同的 hasher 来切换到另一个函数</li> <li>hasher 是实现 BuildHasher trait 的类型</li></ul></div> <footer class="page-edit"><!----> <!----></footer> <!----> </main></div><div class="global-ui"></div></div>
- <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/32.30c1ff3b.js" defer></script>
- </body>
- </html>
|