<buttonid="sidebar-toggle"class="icon-button"type="button"title="Toggle Table of Contents"aria-label="Toggle Table of Contents"aria-controls="sidebar">
<inputtype="search"name="search"id="searchbar"name="searchbar"placeholder="Search this book ..."aria-controls="searchresults-outer"aria-describedby="searchresults-header">
<p>Using a target of a deref coercion can increase the flexibility of your code when you are deciding which argument type to use for a function argument.
In this way, the function will accept more input types.</p>
<p>This is not limited to slice-able or fat pointer types. In fact you should always prefer using the <strong>borrowed type</strong> over <strong>borrowing the owned type</strong>. E.g., <code>&str</code> over <code>&String</code>, <code>&[T]</code> over <code>&Vec<T></code>, or <code>&T</code> over <code>&Box<T></code>.</p>
<p>Using borrowed types you can avoid layers of indirection for those instances where the owned type already provides a layer of indirection. For instance, a <code>String</code> has a layer of indirection, so a <code>&String</code> will have two layers of indrection.
We can avoid this by using <code>&str</code> instead, and letting <code>&String</code> coerce to a <code>&str</code> whenever the function is invoked. </p>
<p>For this example, we will illustrate some differences for using <code>&String</code> as a function argument versus using a <code>&str</code>, but the ideas apply as well to using <code>&Vec<T></code> versus using a <code>&[T]</code> or using a <code>&T</code> versus a <code>&Box<T></code>.</p>
<p>Consider an example where we wish to determine if a word contains three consecutive vowels.
We don't need to own the string to determine this, so we will take a reference.</p>
<p>then both versions will compile and print the same output.</p>
<pre><codeclass="language-bash">Ferris: false
Curious: true
</code></pre>
<p>But wait, that's not all! There is more to this story.
It's likely that you may say to yourself: that doesn't matter, I will never be using a <code>&'static str</code> as an input anways (as we did when we used <code>"Ferris"</code>).
Even ignoring this special example, you may still find that using <code>&str</code> will give you more flexibility than using a <code>&String</code>.</p>
<p>Let's now take an example where someone gives us a sentence, and we want to determine if any of the words in the sentence has a word that contains three consecutive vowels.
We probably should make use of the function we have already defined and simply feed in each word from the sentence.</p>
"Once upon a time, there was a friendly curious crab named Ferris".to_string();
for word in sentence_string.split(' ') {
if three_vowels(word) {
println!("{} has three consecutive vowels!", word);
}
}
}
</code></pre></pre>
<p>Running this example using our function declared with an argument type <code>&str</code> will yield</p>
<pre><codeclass="language-bash">curious has three consecutive vowels!
</code></pre>
<p>However, this example will not run when our function is declared with an argument type <code>&String</code>.
This is because string slices are a <code>&str</code> and not a <code>&String</code> which would require an allocation to be converted to <code>&String</code> which is not implicit, whereas converting from <code>String</code> to <code>&str</code> is cheap and implicit.</p>
<li><ahref="https://doc.rust-lang.org/reference/type-coercions.html">Rust Language Reference on Type Coercions</a></li>
<li>For more discussion on how to handle <code>String</code> and <code>&str</code> see <ahref="https://web.archive.org/web/20201112023149/https://hermanradtke.com/2015/05/03/string-vs-str-in-rust-functions.html">this blog series (2015)</a> by Herman J. Radtke III.</li>
@ -187,13 +187,105 @@ You can break them, but if you do you should have a good reason for it. </p>
<blockquote>
<blockquote>
<p>Code is there for humans, not computers, to understand.</p>
<p>Code is there for humans, not computers, to understand.</p>
</blockquote>
</blockquote>
<h1><aclass="header"href="#concatenating-strings-with-format" id="concatenating-strings-with-format">Concatenating strings with <code>format!</code></a></h1>
<h1><aclass="header"href="#use-borrowed-types-for-arguments" id="use-borrowed-types-for-arguments">Use borrowed types for arguments</a></h1>
<p>Using a target of a deref coercion can increase the flexibility of your code when you are deciding which argument type to use for a function argument.
In this way, the function will accept more input types.</p>
<p>This is not limited to slice-able or fat pointer types. In fact you should always prefer using the <strong>borrowed type</strong> over <strong>borrowing the owned type</strong>. E.g., <code>&str</code> over <code>&String</code>, <code>&[T]</code> over <code>&Vec<T></code>, or <code>&T</code> over <code>&Box<T></code>.</p>
<p>Using borrowed types you can avoid layers of indirection for those instances where the owned type already provides a layer of indirection. For instance, a <code>String</code> has a layer of indirection, so a <code>&String</code> will have two layers of indrection.
We can avoid this by using <code>&str</code> instead, and letting <code>&String</code> coerce to a <code>&str</code> whenever the function is invoked. </p>
<p>For this example, we will illustrate some differences for using <code>&String</code> as a function argument versus using a <code>&str</code>, but the ideas apply as well to using <code>&Vec<T></code> versus using a <code>&[T]</code> or using a <code>&T</code> versus a <code>&Box<T></code>.</p>
<p>Consider an example where we wish to determine if a word contains three consecutive vowels.
We don't need to own the string to determine this, so we will take a reference.</p>
<p>then both versions will compile and print the same output.</p>
<pre><codeclass="language-bash">Ferris: false
Curious: true
</code></pre>
<p>But wait, that's not all! There is more to this story.
It's likely that you may say to yourself: that doesn't matter, I will never be using a <code>&'static str</code> as an input anways (as we did when we used <code>"Ferris"</code>).
Even ignoring this special example, you may still find that using <code>&str</code> will give you more flexibility than using a <code>&String</code>.</p>
<p>Let's now take an example where someone gives us a sentence, and we want to determine if any of the words in the sentence has a word that contains three consecutive vowels.
We probably should make use of the function we have already defined and simply feed in each word from the sentence.</p>
"Once upon a time, there was a friendly curious crab named Ferris".to_string();
for word in sentence_string.split(' ') {
if three_vowels(word) {
println!("{} has three consecutive vowels!", word);
}
}
}
</code></pre></pre>
<p>Running this example using our function declared with an argument type <code>&str</code> will yield</p>
<pre><codeclass="language-bash">curious has three consecutive vowels!
</code></pre>
<p>However, this example will not run when our function is declared with an argument type <code>&String</code>.
This is because string slices are a <code>&str</code> and not a <code>&String</code> which would require an allocation to be converted to <code>&String</code> which is not implicit, whereas converting from <code>String</code> to <code>&str</code> is cheap and implicit.</p>
<li><ahref="https://doc.rust-lang.org/reference/type-coercions.html">Rust Language Reference on Type Coercions</a></li>
<li>For more discussion on how to handle <code>String</code> and <code>&str</code> see <ahref="https://web.archive.org/web/20201112023149/https://hermanradtke.com/2015/05/03/string-vs-str-in-rust-functions.html">this blog series (2015)</a> by Herman J. Radtke III.</li>
</ul>
<h1><aclass="header"href="#concatenating-strings-with-format"id="concatenating-strings-with-format">Concatenating strings with <code>format!</code></a></h1>
<p>Many types in Rust have a <ahref="idioms/ctor.html">constructor</a>. However, this is <em>specific</em> to the
<p>Many types in Rust have a <ahref="idioms/ctor.html">constructor</a>. However, this is <em>specific</em> to the
type; Rust cannot abstract over "everything that has a <code>new()</code> method". To
type; Rust cannot abstract over "everything that has a <code>new()</code> method". To
allow this, the <ahref="https://doc.rust-lang.org/stable/std/default/trait.Default.html"><code>Default</code></a> trait was conceived, which can be used with
allow this, the <ahref="https://doc.rust-lang.org/stable/std/default/trait.Default.html"><code>Default</code></a> trait was conceived, which can be used with
@ -258,7 +350,7 @@ types implement <code>Default</code>, the more useful it becomes.</p>
<p>On the other hand, constructors can take multiple arguments, while the
<p>On the other hand, constructors can take multiple arguments, while the
<code>default()</code> method does not. There can even be multiple constructors with
<code>default()</code> method does not. There can even be multiple constructors with
different names, but there can only be one <code>Default</code> implementation per type.</p>
different names, but there can only be one <code>Default</code> implementation per type.</p>
<h1><aclass="header"href="#memreplace-to-keep-owned-values-in-changed-enums"id="memreplace-to-keep-owned-values-in-changed-enums"><code>mem::replace</code> to keep owned values in changed enums</a></h1>
<h1><aclass="header"href="#memreplace-to-keep-owned-values-in-changed-enums"id="memreplace-to-keep-owned-values-in-changed-enums"><code>mem::replace</code> to keep owned values in changed enums</a></h1>
<p><code>Option</code> can be viewed as a container that contains either zero or one elements. In particular, it implements the <code>IntoIterator</code> trait, and as such can be used with generic code that needs such a type.</p>
<p><code>Option</code> can be viewed as a container that contains either zero or one elements. In particular, it implements the <code>IntoIterator</code> trait, and as such can be used with generic code that needs such a type.</p>
<p>Since <code>Option</code> implements <code>IntoIterator</code>, it can be used as an argument to <ahref="https://doc.rust-lang.org/std/iter/trait.Extend.html#tymethod.extend"><code>.extend()</code></a>:</p>
<p>Since <code>Option</code> implements <code>IntoIterator</code>, it can be used as an argument to <ahref="https://doc.rust-lang.org/std/iter/trait.Extend.html#tymethod.extend"><code>.extend()</code></a>:</p>
@ -622,7 +714,7 @@ for logician in logicians.iter().chain(turing.iter()) {
</span></code></pre></pre>
</span></code></pre></pre>
<p>Note that if the <code>Option</code> is always <code>Some</code>, then it is more idiomatic to use <ahref="https://doc.rust-lang.org/std/iter/fn.once.html"><code>std::iter::once</code></a> on the element instead.</p>
<p>Note that if the <code>Option</code> is always <code>Some</code>, then it is more idiomatic to use <ahref="https://doc.rust-lang.org/std/iter/fn.once.html"><code>std::iter::once</code></a> on the element instead.</p>
<p>Also, since <code>Option</code> implements <code>IntoIterator</code>, it's possible to iterate over it using a <code>for</code> loop. This is equivalent to matching it with <code>if let Some(..)</code>, and in most cases you should prefer the latter.</p>
<p>Also, since <code>Option</code> implements <code>IntoIterator</code>, it's possible to iterate over it using a <code>for</code> loop. This is equivalent to matching it with <code>if let Some(..)</code>, and in most cases you should prefer the latter.</p>
<p><ahref="https://doc.rust-lang.org/std/iter/fn.once.html"><code>std::iter::once</code></a> is an iterator which yields exactly one element. It's a more readable alternative to <code>Some(foo).into_iter()</code>.</p>
<p><ahref="https://doc.rust-lang.org/std/iter/fn.once.html"><code>std::iter::once</code></a> is an iterator which yields exactly one element. It's a more readable alternative to <code>Some(foo).into_iter()</code>.</p>
@ -638,12 +730,12 @@ for logician in logicians.iter().chain(turing.iter()) {
</li>
</li>
</ul>
</ul>
<h1><aclass="header"href="#pass-variables-to-closure"id="pass-variables-to-closure">Pass variables to closure</a></h1>
<h1><aclass="header"href="#pass-variables-to-closure"id="pass-variables-to-closure">Pass variables to closure</a></h1>
<p>The downside of this approach is that you might need to add an otherwise unneeded field to the struct. You can use the <code>()</code> type so that there is no runtime overhead and prepend <code>_</code> to the field name to avoid the unused field warning.</p>
<p>The downside of this approach is that you might need to add an otherwise unneeded field to the struct. You can use the <code>()</code> type so that there is no runtime overhead and prepend <code>_</code> to the field name to avoid the unused field warning.</p>
<p>If Rust allowed private variants of enums, we could use the same trick to make adding a variant to an enum backwards compatible. The problem there is exhaustive match expressions. A private variant would force clients to have a <code>_</code> wildcard pattern.</p>
<p>If Rust allowed private variants of enums, we could use the same trick to make adding a variant to an enum backwards compatible. The problem there is exhaustive match expressions. A private variant would force clients to have a <code>_</code> wildcard pattern.</p>
<p>Instead of typing all of this boiler plate to create an <code>Connection</code> and <code>Request</code> it is easier to just create a wrapping dummy function which takes them as arguments:</p>
<p>Instead of typing all of this boiler plate to create an <code>Connection</code> and <code>Request</code> it is easier to just create a wrapping dummy function which takes them as arguments:</p>
@ -779,11 +871,11 @@ So this pattern is most useful when need <code>no_run</code>. With this, you do
<p>If they are, an alternative can be to create a public method to create a dummy instance which is annotated with <code>#[doc(hidden)]</code> (so that users won't see it).
<p>If they are, an alternative can be to create a public method to create a dummy instance which is annotated with <code>#[doc(hidden)]</code> (so that users won't see it).
Then this method can be called inside of rustdoc because it is part of the crate's public API.</p>
Then this method can be called inside of rustdoc because it is part of the crate's public API.</p>
<pre><codeclass="language-rust ignore">let data = {
<pre><codeclass="language-rust ignore">let data = {
@ -821,9 +913,9 @@ Design patterns are very language-specific - what is a pattern in one language m
<p>If we apply YAGNI to design patterns, we see that the features of Rust allow us to throw out many patterns. For instance, there is no need for the <ahref="https://en.wikipedia.org/wiki/Strategy_pattern">strategy pattern</a> in Rust because we can just use <ahref="https://doc.rust-lang.org/book/traits.html">traits</a>.</p>
<p>If we apply YAGNI to design patterns, we see that the features of Rust allow us to throw out many patterns. For instance, there is no need for the <ahref="https://en.wikipedia.org/wiki/Strategy_pattern">strategy pattern</a> in Rust because we can just use <ahref="https://doc.rust-lang.org/book/traits.html">traits</a>.</p>
<p>TODO: Maybe include some code to illustrate the traits.</p>
<p>TODO: Maybe include some code to illustrate the traits.</p>
<p><ahref="https://doc.rust-lang.org/1.0.0/style/ownership/builders.html">Description in the style guide</a></p>
<p><ahref="https://doc.rust-lang.org/1.0.0/style/ownership/builders.html">Description in the style guide</a></p>
<p><ahref="https://crates.io/crates/derive_builder">derive_builder</a>, a crate for automatically implementing this pattern while avoiding the boilerplate.</p>
<p><ahref="https://crates.io/crates/derive_builder">derive_builder</a>, a crate for automatically implementing this pattern while avoiding the boilerplate.</p>
<p><ahref="patterns/../idioms/ctor.html">Constructor pattern</a> for when construction is simpler.</p>
<p><ahref="patterns/../idioms/ctor.html">Constructor pattern</a> for when construction is simpler.</p>
<h1><aclass="header"href="#compose-structs-together-for-better-borrowing"id="compose-structs-together-for-better-borrowing">Compose structs together for better borrowing</a></h1>
<h1><aclass="header"href="#compose-structs-together-for-better-borrowing"id="compose-structs-together-for-better-borrowing">Compose structs together for better borrowing</a></h1>
<p>Rust has strong static types. This can be very different than what you are used to if you are coming from a loosely-typed language. Don't worry, though. Once you get used to them, you'll find the types actually make your life easier. Why? Because you are making implicit assumptions explicit.</p>
<p>Rust has strong static types. This can be very different than what you are used to if you are coming from a loosely-typed language. Don't worry, though. Once you get used to them, you'll find the types actually make your life easier. Why? Because you are making implicit assumptions explicit.</p>
<p>A really convenient application of the Rust type system is the Newtype pattern.</p>
<p>A really convenient application of the Rust type system is the Newtype pattern.</p>
<p>Here, <code>Bar</code> might be some public, generic type and <code>T1</code> and <code>T2</code> are some internal types. Users of our module shouldn't know that we implement <code>Foo</code> by using a <code>Bar</code>, but what we're really hiding here is the types <code>T1</code> and <code>T2</code>, and how they are used with <code>Bar</code>.</p>
<p>Here, <code>Bar</code> might be some public, generic type and <code>T1</code> and <code>T2</code> are some internal types. Users of our module shouldn't know that we implement <code>Foo</code> by using a <code>Bar</code>, but what we're really hiding here is the types <code>T1</code> and <code>T2</code>, and how they are used with <code>Bar</code>.</p>
<p><ahref="https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization">RAII</a> stands for "Resource Acquisition is Initialisation" which is a terrible
<p><ahref="https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization">RAII</a> stands for "Resource Acquisition is Initialisation" which is a terrible
name. The essence of the pattern is that resource initialisation is done in the
name. The essence of the pattern is that resource initialisation is done in the
constructor of an object and finalisation in the destructor. This pattern is
constructor of an object and finalisation in the destructor. This pattern is
extended in Rust by using an RAII object as a guard of some resource and relying
extended in Rust by using an RAII object as a guard of some resource and relying
on the type system to ensure that access is always mediated by the guard object.</p>
on the type system to ensure that access is always mediated by the guard object.</p>
<p>Prefer small crates that do one thing well.</p>
<p>Prefer small crates that do one thing well.</p>
<p>Cargo and crates.io make it easy to add third-party libraries, much more so than in say C or C++. Moreover, since packages on crates.io cannot be edited or removed after publication, any build that works now should continue to work in the future. We should take advantage of this tooling, and use smaller, more fine-grained dependencies.</p>
<p>Cargo and crates.io make it easy to add third-party libraries, much more so than in say C or C++. Moreover, since packages on crates.io cannot be edited or removed after publication, any build that works now should continue to work in the future. We should take advantage of this tooling, and use smaller, more fine-grained dependencies.</p>
<p>The <ahref="https://crates.io/crates/ref_slice"><code>ref_slice</code></a> crate provides functions for converting <code>&T</code> to <code>&[T]</code>.</p>
<p>The <ahref="https://crates.io/crates/ref_slice"><code>ref_slice</code></a> crate provides functions for converting <code>&T</code> to <code>&[T]</code>.</p>
<p>The <ahref="https://crates.io/crates/url"><code>url</code></a> crate provides tools for working with URLs.</p>
<p>The <ahref="https://crates.io/crates/url"><code>url</code></a> crate provides tools for working with URLs.</p>
<p>The <ahref="https://crates.io/crates/num_cpus"><code>num_cpus</code></a> crate provides a function to query the number of CPUs on a machine.</p>
<p>The <ahref="https://crates.io/crates/num_cpus"><code>num_cpus</code></a> crate provides a function to query the number of CPUs on a machine.</p>
<p>If you have <code>unsafe</code> code, create the smallest possible module that can uphold the needed invariants to build a minimal safe interface upon the unsafety. Embed this into a larger module that contains only safe code and presents an ergonomic interface. Note that the outer module can contain unsafe functions and methods that call directly into the unsafe code. Users may use this to gain speed benefits.</p>
<p>If you have <code>unsafe</code> code, create the smallest possible module that can uphold the needed invariants to build a minimal safe interface upon the unsafety. Embed this into a larger module that contains only safe code and presents an ergonomic interface. Note that the outer module can contain unsafe functions and methods that call directly into the unsafe code. Users may use this to gain speed benefits.</p>
<li>The <ahref="https://docs.rs/toolshed"><code>toolshed</code></a> crate contains its unsafe operations in submodules, presenting a safe interface to users.</li>
<li>The <ahref="https://docs.rs/toolshed"><code>toolshed</code></a> crate contains its unsafe operations in submodules, presenting a safe interface to users.</li>
<li><code>std</code>s <code>String</code> class is a wrapper over <code>Vec<u8></code> with the added invariant that the contents must be valid UTF-8. The operations on <code>String</code> ensure this behavior. However, users have the option of using an <code>unsafe</code> method to create a <code>String</code>, in which case the onus is on them to guarantee the validity of the contents.</li>
<li><code>std</code>s <code>String</code> class is a wrapper over <code>Vec<u8></code> with the added invariant that the contents must be valid UTF-8. The operations on <code>String</code> ensure this behavior. However, users have the option of using an <code>unsafe</code> method to create a <code>String</code>, in which case the onus is on them to guarantee the validity of the contents.</li>