mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 21:41:18 -06:00
378 lines
26 KiB
HTML
378 lines
26 KiB
HTML
<!DOCTYPE HTML>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title>The Rust Programming Language</title>
|
||
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
||
<meta name="description" content="">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
|
||
<base href="">
|
||
|
||
<link rel="stylesheet" href="book.css">
|
||
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
|
||
|
||
<link rel="shortcut icon" href="favicon.png">
|
||
|
||
<!-- Font Awesome -->
|
||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
|
||
|
||
<link rel="stylesheet" href="highlight.css">
|
||
<link rel="stylesheet" href="tomorrow-night.css">
|
||
|
||
<!-- MathJax -->
|
||
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
|
||
|
||
<!-- Fetch JQuery from CDN but have a local fallback -->
|
||
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
|
||
<script>
|
||
if (typeof jQuery == 'undefined') {
|
||
document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
|
||
}
|
||
</script>
|
||
</head>
|
||
<body class="light">
|
||
<!-- Set the theme before any content is loaded, prevents flash -->
|
||
<script type="text/javascript">
|
||
var theme = localStorage.getItem('theme');
|
||
if (theme == null) { theme = 'light'; }
|
||
$('body').removeClass().addClass(theme);
|
||
</script>
|
||
|
||
<!-- Hide / unhide sidebar before it is displayed -->
|
||
<script type="text/javascript">
|
||
var sidebar = localStorage.getItem('sidebar');
|
||
if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
|
||
else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
|
||
</script>
|
||
|
||
<div id="sidebar" class="sidebar">
|
||
<ul class="chapter"><li><a href="ch01-00-introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="ch01-01-installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="ch01-02-hello-world.html"><strong>1.2.</strong> Hello, World!</a></li></ul></li><li><a href="ch02-00-guessing-game-tutorial.html"><strong>2.</strong> Guessing Game Tutorial</a></li><li><a href="ch03-00-common-programming-concepts-in-rust.html"><strong>3.</strong> Common Programming Concepts in Rust</a></li><li><ul class="section"><li><a href="ch03-01-variables-and-mutability.html"><strong>3.1.</strong> Variables and Mutability</a></li><li><a href="ch03-02-data-types.html"><strong>3.2.</strong> Data Types</a></li><li><a href="ch03-03-how-functions-work.html"><strong>3.3.</strong> How Functions Work</a></li><li><a href="ch03-04-comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="ch03-05-control-flow.html"><strong>3.5.</strong> Control Flow</a></li></ul></li><li><a href="ch04-00-understanding-ownership.html"><strong>4.</strong> Understanding Ownership</a></li><li><ul class="section"><li><a href="ch04-01-ownership.html"><strong>4.1.</strong> Ownership</a></li><li><a href="ch04-02-references-and-borrowing.html"><strong>4.2.</strong> References & Borrowing</a></li><li><a href="ch04-03-slices.html"><strong>4.3.</strong> Slices</a></li></ul></li><li><a href="ch05-00-structs.html"><strong>5.</strong> Structs</a></li><li><ul class="section"><li><a href="ch05-01-method-syntax.html"><strong>5.1.</strong> Method Syntax</a></li></ul></li><li><a href="ch06-00-enums.html"><strong>6.</strong> Enums</a></li><li><ul class="section"><li><a href="ch06-01-option.html"><strong>6.1.</strong> Option</a></li><li><a href="ch06-02-match.html"><strong>6.2.</strong> Match</a></li><li><a href="ch06-03-if-let.html"><strong>6.3.</strong> <code>if let</code></a></li></ul></li><li><a href="ch07-00-modules.html"><strong>7.</strong> Modules</a></li><li><ul class="section"><li><a href="ch07-01-mod-and-the-filesystem.html"><strong>7.1.</strong> <code>mod</code> and the Filesystem</a></li><li><a href="ch07-02-controlling-visibility-with-pub.html"><strong>7.2.</strong> Controlling Visibility with <code>pub</code></a></li><li><a href="ch07-03-importing-names-with-use.html"><strong>7.3.</strong> Importing Names with <code>use</code></a></li></ul></li><li><a href="ch08-00-fundamental-collections.html"><strong>8.</strong> Fundamental Collections</a></li><li><ul class="section"><li><a href="ch08-01-vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="ch08-02-strings.html" class="active"><strong>8.2.</strong> Strings</a></li><li><a href="ch08-03-hash-maps.html"><strong>8.3.</strong> Hash Maps</a></li></ul></li><li><a href="ch09-00-error-handling.html"><strong>9.</strong> Error Handling</a></li><li><ul class="section"><li><a href="ch09-01-unrecoverable-errors-with-panic.html"><strong>9.1.</strong> Unrecoverable Errors with <code>panic!</code></a></li><li><a href="ch09-02-recoverable-errors-with-result.html"><strong>9.2.</strong> Recoverable Errors with <code>Result</code></a></li><li><a href="ch09-03-to-panic-or-not-to-panic.html"><strong>9.3.</strong> To <code>panic!</code> or Not To <code>panic!</code></a></li></ul></li><li><strong>10.</strong> Generics</li><li><strong>11.</strong> I/O</li><li><ul class="section"><li><strong>11.1.</strong> <code>Read</code> & <code>Write</code></li><li><strong>11.2.</strong> <code>std::fs</code></li><li><strong>11.3.</strong> <code>std::path</code></li><li><strong>11.4.</strong> <code>std::env</code></li></ul></li><li><strong>12.</strong> Testing</li><li><ul class="section"><li><strong>12.1.</strong> Unit Tests</li><li><strong>12.2.</strong> Integration Tests</li><li><strong>12.3.</strong> Test Attribute</li></ul></li><li><strong>13.</strong> Composition</li><li><ul class="section"><li><strong>13.1.</strong> Instead of Inheritance</li><li><strong>13.2.</strong> Trait Objects?</li></ul></li><li><strong>14.</strong> Creating a Library</li><li><ul class="section"><li><strong>14.1.</strong> Cargo</li><li><strong>14.2.</strong> Crates.io</li><li><a href="chYY-YY-public-api.html"><strong>14.3.</strong> Organizing your Public API</a></li><li><a href="chYY-YY-documentation.html"><strong>14.4.</strong> Documentation</a></li><li><a href="chYY-YY-workspaces.html"><strong>14.5.</strong> Workspaces and Multiple Related Crates</a></li></ul></li><li><strong>15.</strong> Closures</li><li><strong>16.</strong> Zero-cost Abstractions</li><li><ul class="section"><li><strong>16.1.</strong> Iterators as a Case Study</li></ul></li><li><strong>17.</strong> Smart Pointers</li><li><ul class="section"><li><strong>17.1.</strong> <code>Box<T></code></li><li><strong>17.2.</strong> <code>Rc<T></code></li><li><strong>17.3.</strong> <code>Cell</code></li><li><strong>17.4.</strong> <code>RefCell</code></li><li><strong>17.5.</strong> Interior Mutability</li></ul></li><li><strong>18.</strong> Concurrency</li><li><ul class="section"><li><strong>18.1.</strong> Threads</li><li><strong>18.2.</strong> <code>Send</code> & <code>Sync</code></li><li><strong>18.3.</strong> <code>Arc<T></code></li><li><strong>18.4.</strong> <code>Mutex<T></code></li><li><strong>18.5.</strong> <code>Channels</code></li></ul></li><li><a href="chXX-patterns.html"><strong>19.</strong> Patterns</a></li><li><strong>20.</strong> More Lifetimes</li><li><strong>21.</strong> Unsafe Rust</li><li><ul class="section"><li><strong>21.1.</strong> Raw Pointers</li><li><strong>21.2.</strong> <code>transmute</code></li></ul></li><li><strong>22.</strong> Foreign Function Interface</li><li><ul class="section"><li><strong>22.1.</strong> Conditional Compilation</li><li><strong>22.2.</strong> Bindings to C</li><li><strong>22.3.</strong> Using Rust from Other Languages</li><li><strong>22.4.</strong> <code>static</code></li></ul></li><li><strong>23.</strong> Advanced Type System Features</li><li><ul class="section"><li><strong>23.1.</strong> Associated Types</li><li><strong>23.2.</strong> Trait Objects</li><li><strong>23.3.</strong> UFCS</li><li><strong>23.4.</strong> Coherence</li></ul></li><li><strong>24.</strong> Macros</li><li><ul class="section"><li><strong>24.1.</strong> Writing Your Own Macros</li></ul></li><li><strong>25.</strong> Nightly Rust</li><li><ul class="section"><li><strong>25.1.</strong> Nightly Features</li><li><strong>25.2.</strong> How to Find Out About Nightly Features</li></ul></li><li><a href="appendix-00.html"><strong>26.</strong> Appendix</a></li><li><ul class="section"><li><a href="appendix-01-keywords.html"><strong>26.1.</strong> Keywords</a></li><li><a href="appendix-02-operators.html"><strong>26.2.</strong> Operators</a></li><li><a href="appendix-03-derivable-traits.html"><strong>26.3.</strong> Derivable Traits</a></li></ul></li></ul>
|
||
</div>
|
||
|
||
<div id="page-wrapper" class="page-wrapper">
|
||
|
||
<div class="page">
|
||
<div id="menu-bar" class="menu-bar">
|
||
<div class="left-buttons">
|
||
<i id="sidebar-toggle" class="fa fa-bars"></i>
|
||
<i id="theme-toggle" class="fa fa-paint-brush"></i>
|
||
</div>
|
||
|
||
<h1 class="menu-title">The Rust Programming Language</h1>
|
||
|
||
<div class="right-buttons">
|
||
<i id="print-button" class="fa fa-print" title="Print this book"></i>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="content" class="content">
|
||
<h2>Strings</h2>
|
||
<p>We've already talked about strings a bunch in Chapter 4, but let's take a more
|
||
in-depth look at them now.</p>
|
||
<h3>Many Kinds of Strings</h3>
|
||
<p>Strings are a common place for new Rustaceans to get stuck. This is due to a
|
||
combination of three things: Rust's propensity for making sure to expose
|
||
possible errors, strings being a more complicated data structure than many
|
||
programmers give them credit for, and UTF-8. These things combine in a way that
|
||
can seem difficult coming from other languages.</p>
|
||
<p>Before we can dig into those aspects, we need to talk about what exactly we
|
||
even mean by the word 'string'. Rust actually only has one string type in the
|
||
core language itself: <code>&str</code>. We talked about <em>string slices</em> in Chapter 4:
|
||
they're a reference to some UTF-8 encoded string data stored somewhere else.
|
||
String literals, for example, are stored in the binary output of the program,
|
||
and are therefore string slices.</p>
|
||
<p>Rust's standard library is what provides the type called <code>String</code>. This is a
|
||
growable, mutable, owned, UTF-8 encoded string type. When Rustaceans talk about
|
||
'strings' in Rust, they usually mean "<code>String</code> and <code>&str</code>". This chapter is
|
||
largely about <code>String</code>, and these two types are used heavily in Rust's standard
|
||
library. Both <code>String</code> and string slices are UTF-8 encoded.</p>
|
||
<p>Rust's standard library also includes a number of other string types, such as
|
||
<code>OsString</code>, <code>OsStr</code>, <code>CString</code>, and <code>CStr</code>. Library crates may provide even
|
||
more options for storing string data. Similarly to the <code>*String</code>/<code>*Str</code> naming,
|
||
they often provide an owned and borrowed variant, just like <code>String</code>/<code>&str</code>.
|
||
These string types may store different encodings or be represented in memory in
|
||
a different way, for example. We won't be talking about these other string
|
||
types in this chapter; see their API documentation for more about how to use
|
||
them and when each is appropriate.</p>
|
||
<h3>Creating a New String</h3>
|
||
<p>Let's look at how to do the same operations on <code>String</code> as we did with <code>Vec</code>,
|
||
starting with creating one. Similarly, <code>String</code> has <code>new</code>:</p>
|
||
<pre><code class="language-rust">let s = String::new();
|
||
</code></pre>
|
||
<p>Often, we'll have some initial data that we'd like to start the string off with.
|
||
For that, there's the <code>to_string</code> method:</p>
|
||
<pre><code class="language-rust">let data = "initial contents";
|
||
|
||
let s = data.to_string();
|
||
|
||
// the method also works on a literal directly:
|
||
let s = "initial contents".to_string();
|
||
</code></pre>
|
||
<p>This form is equivalent to using <code>to_string</code>:</p>
|
||
<pre><code class="language-rust">let s = String::from("Initial contents");
|
||
</code></pre>
|
||
<p>Since strings are used for so many things, there are many different generic
|
||
APIs that make sense for strings. There are a lot of options, and some of them
|
||
can feel redundant because of this, but they all have their place! In this
|
||
case, <code>String::from</code> and <code>.to_string</code> end up doing the exact same thing, so
|
||
which you choose is a matter of style. Some people use <code>String::from</code> for
|
||
literals, and <code>.to_string</code> for variables. Most Rust style is pretty
|
||
uniform, but this specific question is one of the most debated.</p>
|
||
<p>Remember that strings are UTF-8 encoded, so we can include any properly encoded
|
||
data in them:</p>
|
||
<pre><code class="language-rust">let hello = "السلام عليكم";
|
||
let hello = "Dobrý den";
|
||
let hello = "Hello";
|
||
let hello = "שָׁלוֹם";
|
||
let hello = "नमस्ते";
|
||
let hello = "こんにちは";
|
||
let hello = "안녕하세요";
|
||
let hello = "你好";
|
||
let hello = "Olá";
|
||
let hello = "Здравствуйте";
|
||
let hello = "Hola";
|
||
</code></pre>
|
||
<h3>Updating a String</h3>
|
||
<p>A <code>String</code> can be changed and can grow in size, just like a <code>Vec</code> can.</p>
|
||
<h4>Push</h4>
|
||
<p>We can grow a <code>String</code> by using the <code>push_str</code> method to append another
|
||
string:</p>
|
||
<pre><code class="language-rust">let mut s = String::from("foo");
|
||
s.push_str("bar");
|
||
</code></pre>
|
||
<p><code>s</code> will contain "foobar" after these two lines.</p>
|
||
<p>The <code>push</code> method will add a <code>char</code>:</p>
|
||
<pre><code class="language-rust">let mut s = String::from("lo");
|
||
s.push('l');
|
||
</code></pre>
|
||
<p><code>s</code> will contain "lol" after this point.</p>
|
||
<p>We can make any <code>String</code> contain the empty string with the <code>clear</code> method:</p>
|
||
<pre><code class="language-rust">let mut s = String::from("Noooooooooooooooooooooo!");
|
||
s.clear();
|
||
</code></pre>
|
||
<p>Now <code>s</code> will be the empty string, "".</p>
|
||
<h4>Concatenation</h4>
|
||
<p>Often, we'll want to combine two strings together. One way is to use the <code>+</code>
|
||
operator:</p>
|
||
<pre><code class="language-rust">let s1 = String::from("Hello, ");
|
||
let s2 = String::from("world!");
|
||
let s3 = s1 + &s2;
|
||
</code></pre>
|
||
<p>This code will make <code>s3</code> contain "Hello, world!" There's some tricky bits here,
|
||
though, that come from the type signature of <code>+</code> for <code>String</code>. The signature
|
||
for the <code>add</code> method that the <code>+</code> operator uses looks something like this:</p>
|
||
<pre><code class="language-rust,ignore">fn add(self, s: &str) -> String {
|
||
</code></pre>
|
||
<p>This isn't exactly what the actual signature is in the standard library because
|
||
<code>add</code> is defined using generics there. Here, we're just looking at what the
|
||
signature of the method would be if <code>add</code> was defined specifically for
|
||
<code>String</code>. This signature gives us the clues we need in order to understand the
|
||
tricky bits of <code>+</code>.</p>
|
||
<p>First of all, <code>s2</code> has an <code>&</code>. This is because of the <code>s</code> argument in the <code>add</code>
|
||
function: we can only add a <code>&str</code> to a <code>String</code>, we can't add two <code>String</code>s
|
||
together. Remember back in Chapter 4 when we talked about how <code>&String</code> will
|
||
coerce to <code>&str</code>: we write <code>&s2</code> so that the <code>String</code> will coerce to the proper
|
||
type, <code>&str</code>.</p>
|
||
<p>Secondly, <code>add</code> takes ownership of <code>self</code>, which we can tell because <code>self</code>
|
||
does <em>not</em> have an <code>&</code> in the signature. This means <code>s1</code> in the above example
|
||
will be moved into the <code>add</code> call and no longer be a valid variable after that.
|
||
So while <code>let s3 = s1 + &s2;</code> looks like it will copy both strings and create a
|
||
new one, this statement actually takes ownership of <code>s1</code>, appends a copy of
|
||
<code>s2</code>'s contents, then returns ownership of the result. In other words, it looks
|
||
like it's making a lot of copies, but isn't: the implementation is more
|
||
efficient than copying.</p>
|
||
<p>If we need to concatenate multiple strings, this behavior of <code>+</code> gets
|
||
unwieldy:</p>
|
||
<pre><code class="language-rust">let s1 = String::from("tic");
|
||
let s2 = String::from("tac");
|
||
let s3 = String::from("toe");
|
||
|
||
let s = s1 + "-" + &s2 + "-" + &s3;
|
||
</code></pre>
|
||
<p><code>s</code> will be "tic-tac-toe" at this point. With all of the <code>+</code> and <code>"</code>
|
||
characters, it gets hard to see what's going on. For more complicated string
|
||
combining, we can use the <code>format!</code> macro:</p>
|
||
<pre><code class="language-rust">let s1 = String::from("tic");
|
||
let s2 = String::from("tac");
|
||
let s3 = String::from("toe");
|
||
|
||
let s = format!("{}-{}-{}", s1, s2, s3);
|
||
</code></pre>
|
||
<p>This code will also set <code>s</code> to "tic-tac-toe". The <code>format!</code> macro works in the
|
||
same way as <code>println!</code>, but instead of printing the output to the screen, it
|
||
returns a <code>String</code> with the contents. This version is much easier to read than
|
||
all of the <code>+</code>s.</p>
|
||
<h3>Indexing into Strings</h3>
|
||
<p>In many other languages, accessing individual characters in a string by
|
||
referencing the characters by index is a valid and common operation. In Rust,
|
||
however, if we try to access parts of a <code>String</code> using indexing syntax, we'll
|
||
get an error. That is, this code:</p>
|
||
<pre><code class="language-rust,ignore">let s1 = String::from("hello");
|
||
let h = s1[0];
|
||
</code></pre>
|
||
<p>will result in this error:</p>
|
||
<pre><code class="language-text">error: the trait bound `std::string::String: std::ops::Index<_>` is not
|
||
satisfied [--explain E0277]
|
||
|>
|
||
|> let h = s1[0];
|
||
|> ^^^^^
|
||
note: the type `std::string::String` cannot be indexed by `_`
|
||
</code></pre>
|
||
<p>The error and the note tell the story: Rust strings don't support indexing. So
|
||
the follow-up question is, why not? In order to answer that, we have to talk a
|
||
bit about how Rust stores strings in memory.</p>
|
||
<h4>Internal Representation</h4>
|
||
<p>A <code>String</code> is a wrapper over a <code>Vec<u8></code>. Let's take a look at some of our
|
||
properly-encoded UTF-8 example strings from before. First, this one:</p>
|
||
<pre><code class="language-rust">let len = "Hola".len();
|
||
</code></pre>
|
||
<p>In this case, <code>len</code> will be four, which means the <code>Vec</code> storing the string
|
||
"Hola" is four bytes long: each of these letters takes one byte when encoded in
|
||
UTF-8. What about this example, though?</p>
|
||
<pre><code class="language-rust">let len = "Здравствуйте".len();
|
||
</code></pre>
|
||
<p>There are two answers that potentially make sense here: the first is 12, which
|
||
is the number of letters that a person would count if we asked someone how long
|
||
this string was. The second, though, is what Rust's answer is: 24. This is the
|
||
number of bytes that it takes to encode "Здравствуйте" in UTF-8, because each
|
||
character takes two bytes of storage.</p>
|
||
<p>By the same token, imagine this invalid Rust code:</p>
|
||
<pre><code class="language-rust,ignore">let hello = "Здравствуйте";
|
||
let answer = &h[0];
|
||
</code></pre>
|
||
<p>What should the value of <code>answer</code> be? Should it be <code>З</code>, the first letter? When
|
||
encoded in UTF-8, the first byte of <code>З</code> is <code>208</code>, and the second is <code>151</code>. So
|
||
should <code>answer</code> be <code>208</code>? <code>208</code> is not a valid character on its own, though.
|
||
Plus, for Latin letters, this would not return the answer most people would
|
||
expect: <code>&"hello"[0]</code> would then return <code>104</code>, not <code>h</code>.</p>
|
||
<h4>Bytes and Scalar Values and Grapheme Clusters! Oh my!</h4>
|
||
<p>This leads to another point about UTF-8: there are really three relevant ways
|
||
to look at strings, from Rust's perspective: bytes, scalar values, and grapheme
|
||
clusters. If we look at the string "नमस्ते", it is ultimately stored as a <code>Vec</code>
|
||
of <code>u8</code> values that looks like this:</p>
|
||
<pre><code class="language-text">[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 165, 135]
|
||
</code></pre>
|
||
<p>That's 18 bytes. But if we look at them as Unicode scalar values, which are
|
||
what Rust's <code>char</code> type is, those bytes look like this:</p>
|
||
<pre><code class="language-text">['न', 'म', 'स', '्', 'त', 'े']
|
||
</code></pre>
|
||
<p>There are six <code>char</code> values here. Finally, if we look at them as grapheme
|
||
clusters, which is the closest thing to what humans would call 'letters', we'd
|
||
get this:</p>
|
||
<pre><code class="language-text">["न", "म", "स्", "ते"]
|
||
</code></pre>
|
||
<p>Four elements! It turns out that even within 'grapheme cluster', there are
|
||
multiple ways of grouping things. Convinced that strings are actually really
|
||
complicated yet?</p>
|
||
<p>Another reason that indexing into a <code>String</code> to get a character is not available
|
||
is that indexing operations are expected to always be fast. This isn't possible
|
||
with a <code>String</code>, since Rust would have to walk through the contents from the
|
||
beginning to the index to determine how many valid characters there were, no
|
||
matter how we define "character".</p>
|
||
<p>All of these problems mean that Rust does not implement <code>[]</code> for <code>String</code>, so
|
||
we cannot directly do this.</p>
|
||
<h3>Slicing Strings</h3>
|
||
<p>However, indexing the bytes of a string is very useful, and is not expected to
|
||
be fast. While we can't use <code>[]</code> with a single number, we <em>can</em> use <code>[]</code> with
|
||
a range to create a string slice from particular bytes:</p>
|
||
<pre><code class="language-rust">let hello = "Здравствуйте";
|
||
|
||
let s = &hello[0..4];
|
||
</code></pre>
|
||
<p>Here, <code>s</code> will be a <code>&str</code> that contains the first four bytes of the string.
|
||
Earlier, we mentioned that each of these characters was two bytes, so that means
|
||
that <code>s</code> will be "Зд".</p>
|
||
<p>What would happen if we did <code>&hello[0..1]</code>? The answer: it will panic at
|
||
runtime, in the same way that accessing an invalid index in a vector does:</p>
|
||
<pre><code class="language-bash">thread 'main' panicked at 'index 0 and/or 1 in `Здравствуйте` do not lie on
|
||
character boundary', ../src/libcore/str/mod.rs:1694
|
||
</code></pre>
|
||
<h3>Methods for Iterating Over Strings</h3>
|
||
<p>If we do need to perform operations on individual characters, the best way to
|
||
do that is using the <code>chars</code> method. Calling <code>chars</code> on "नमस्ते" gives us the six
|
||
Rust <code>char</code> values:</p>
|
||
<pre><code class="language-rust">for c in "नमस्ते".chars() {
|
||
println!("{}", c);
|
||
}
|
||
</code></pre>
|
||
<p>This code will print:</p>
|
||
<pre><code class="language-bash">न
|
||
म
|
||
स
|
||
्
|
||
त
|
||
े
|
||
</code></pre>
|
||
<p>The <code>bytes</code> method returns each raw byte, which might be appropriate for your
|
||
domain, but remember that valid UTF-8 characters may be made up of more than
|
||
one byte:</p>
|
||
<pre><code class="language-rust">for b in "नमस्ते".bytes() {
|
||
println!("{}", b);
|
||
}
|
||
</code></pre>
|
||
<p>This code will print the 18 bytes that make up this <code>String</code>, starting with:</p>
|
||
<pre><code class="language-bash">224
|
||
164
|
||
168
|
||
224
|
||
// ... etc
|
||
</code></pre>
|
||
<p>There are crates available on crates.io to get grapheme clusters from <code>String</code>s.</p>
|
||
<p>To summarize, strings are complicated. Different programming languages make
|
||
different choices about how to present this complexity to the programmer. Rust
|
||
has chosen to attempt to make correct handling of <code>String</code> data be the default
|
||
for all Rust programs, which does mean programmers have to put more thought
|
||
into handling UTF-8 data upfront. This tradeoff exposes us to more of the
|
||
complexity of strings than we have to handle in other languages, but will
|
||
prevent us from having to handle errors involving non-ASCII characters later in
|
||
our development lifecycle.</p>
|
||
<p>Let's switch to something a bit less complex: Hash Map!</p>
|
||
|
||
</div>
|
||
|
||
<!-- Mobile navigation buttons -->
|
||
|
||
<a href="ch08-01-vectors.html" class="mobile-nav-chapters previous">
|
||
<i class="fa fa-angle-left"></i>
|
||
</a>
|
||
|
||
|
||
|
||
<a href="ch08-03-hash-maps.html" class="mobile-nav-chapters next">
|
||
<i class="fa fa-angle-right"></i>
|
||
</a>
|
||
|
||
|
||
</div>
|
||
|
||
|
||
<a href="ch08-01-vectors.html" class="nav-chapters previous" title="You can navigate through the chapters using the arrow keys">
|
||
<i class="fa fa-angle-left"></i>
|
||
</a>
|
||
|
||
|
||
|
||
<a href="ch08-03-hash-maps.html" class="nav-chapters next" title="You can navigate through the chapters using the arrow keys">
|
||
<i class="fa fa-angle-right"></i>
|
||
</a>
|
||
|
||
|
||
</div>
|
||
|
||
|
||
<!-- Local fallback for Font Awesome -->
|
||
<script>
|
||
if ($(".fa").css("font-family") !== "FontAwesome") {
|
||
$('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
|
||
}
|
||
</script>
|
||
|
||
<!-- Livereload script (if served using the cli tool) -->
|
||
|
||
|
||
<script src="highlight.js"></script>
|
||
<script src="book.js"></script>
|
||
</body>
|
||
</html>
|