<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="/atom.xsl"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en-AU">
	<title>Chris Morgan’s blog posts tagged Rust</title>
	<subtitle type="html">I write about Rust things routinely. Here they all are.</subtitle>
	<link href="https://chrismorgan.info/blog/tags/rust/feed.xml" rel="self" type="application/atom+xml"/>
	<link href="https://chrismorgan.info"/>
	<updated>2022-04-01T00:00:00+00:00</updated>
	<id>https://chrismorgan.info/blog/tags/rust/feed.xml</id>
	<author>
		<name>Chris Morgan</name>
		<uri>https://chrismorgan.info</uri>
		<email>me@chrismorgan.info</email>
	</author>
	<entry xml:base="https://chrismorgan.info/blog/U+/">
		<title type="html">&lt;strong&gt;U+:&lt;/strong&gt; pretty Unicode code point literals for Rust</title>
		<published>2022-04-01T00:00:00+00:00</published>
		<updated>2022-04-01T00:00:00+00:00</updated>
		<link href="https://chrismorgan.info/blog/U+/" type="text/html"/>
		<id>https://chrismorgan.info/blog/U+/</id>
		<category scheme="https://chrismorgan.info/blog/tags/" term="rust" label="Rust" />
		<category scheme="https://chrismorgan.info/blog/tags/" term="fun" label="Fun" />
		<content type="html">
			&lt;p class=intro&gt;Stop worrying about whether char literal syntax uses &lt;code&gt;&lt;span class=s&gt;&apos;&lt;b&gt;&lt;i&gt;\u{1234}&lt;/i&gt;&lt;/b&gt;&apos;&lt;/span&gt;&lt;/code&gt;, &lt;code&gt;&lt;span class=s&gt;&quot;&lt;b&gt;&lt;i&gt;\u1234&lt;/i&gt;&lt;/b&gt;&quot;&lt;/span&gt;&lt;/code&gt;, &lt;code&gt;&lt;span class=s&gt;&lt;b&gt;&lt;i&gt;\x1E\x88\xB4&lt;/i&gt;&lt;/b&gt;&lt;/span&gt;&lt;/code&gt; or something else, and use the True Unicode Syntax of &lt;code&gt;&lt;span class=n&gt;U+1234&lt;/span&gt;&lt;/code&gt;!
			&lt;p&gt;I was reading &lt;a href=&quot;https://uncyclopedia.com/wiki/Rust_(programming_language)&quot;&gt;https://uncyclopedia.com/wiki/Rust_(programming_language)&lt;/a&gt;
for some reason, and read &lt;code&gt;&lt;b&gt;let&lt;/b&gt; U = &lt;span class=n&gt;0&lt;/span&gt;; U = U + &lt;span class=n&gt;1&lt;/span&gt;;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Suddenly my mind was awhirl with a Concept. I implemented it at once.&lt;/p&gt;
&lt;h2 id=&quot;the-problem&quot;&gt;The problem&lt;/h2&gt;
&lt;p&gt;Unicode expresses its code points in syntax like &lt;strong&gt;U+1234&lt;/strong&gt; (full range U+0000–U+10FFFF).&lt;/p&gt;
&lt;p&gt;But then when you want to transfer it to a programming language,
you have to learn another syntax. Will it be &lt;code&gt;&lt;span class=s&gt;&apos;&lt;b&gt;&lt;i&gt;\u1234&lt;/i&gt;&lt;/b&gt;&apos;&lt;/span&gt;&lt;/code&gt;, &lt;code&gt;&lt;span class=s&gt;&apos;&lt;b&gt;&lt;i&gt;\u{1234}&lt;/i&gt;&lt;/b&gt;&apos;&lt;/span&gt;&lt;/code&gt;,
&lt;code&gt;&lt;span class=s&gt;&amp;quot;&lt;b&gt;&lt;i&gt;\x1E\x88\xB4&lt;/i&gt;&lt;/b&gt;&amp;quot;&lt;/span&gt;&lt;/code&gt;, &lt;code&gt;&lt;b class=s&gt;&lt;i&gt;\341\210\264&lt;/i&gt;&lt;/b&gt;&lt;/code&gt;, something else?&lt;/p&gt;
&lt;p&gt;And then astral plane characters make it even worse:
&lt;code&gt;&lt;span class=s&gt;&amp;quot;&lt;b&gt;&lt;i&gt;\U0001F631&lt;/i&gt;&lt;/b&gt;&amp;quot;&lt;/span&gt;&lt;/code&gt;, &lt;code&gt;&lt;span class=s&gt;&apos;&lt;b&gt;&lt;i&gt;\u{1F631}&lt;/i&gt;&lt;/b&gt;&apos;&lt;/span&gt;&lt;/code&gt;, &lt;code&gt;&lt;b class=s&gt;&lt;i&gt;\xF0\x9F\x98\xB1&lt;/i&gt;&lt;/b&gt;&lt;/code&gt;, &lt;code&gt;&lt;span class=s&gt;&amp;quot;&lt;b&gt;&lt;i&gt;\uD83D\uDE31&lt;/i&gt;&lt;/b&gt;&amp;quot;&lt;/span&gt;&lt;/code&gt;
(with all the associated pain the abomination UTF-16 entails,
especially that your char type may simply not be able to represent this),
something else?&lt;/p&gt;
&lt;p&gt;And so here is this crate that lets you use the True Unicode Syntax in Rust:&lt;/p&gt;
&lt;figure&gt;&lt;pre&gt;&lt;b&gt;use&lt;/b&gt; u_plus::U;

&lt;i&gt;assert_eq!&lt;/i&gt;(&lt;!-- There, I *knew* manual syntax highlighting would come in handy at some point. --&gt;&lt;span class=n&gt;U+1234&lt;/span&gt;, &lt;span class=s&gt;&apos;&lt;i&gt;&lt;b&gt;\u{1234}&lt;/b&gt;&lt;/i&gt;&apos;&lt;/span&gt;);&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;So forget about &lt;code&gt;&lt;b class=s&gt;&lt;i&gt;\u{…}&lt;/i&gt;&lt;/b&gt;&lt;/code&gt; syntax and use &lt;code&gt;&lt;span class=n&gt;U+…&lt;/span&gt;&lt;/code&gt; literals!&lt;/p&gt;
&lt;p&gt;(Caution: there are some limitations with this approach, see &lt;a href=&quot;https://git.chrismorgan.info/u-plus/blob/HEAD:/KNOWN_ISSUES.md&quot;&gt;KNOWN_ISSUES.md&lt;/a&gt; for details.)&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;links&quot;&gt;Links&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;The &lt;code&gt;u-plus&lt;/code&gt; crate on &lt;a href=&quot;https://crates.io/crates/u-plus&quot;&gt;crates.io&lt;/a&gt; (or see on &lt;a href=&quot;https://lib.rs/crates/u-plus&quot;&gt;lib.rs&lt;/a&gt;).&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;The &lt;a href=&quot;https://git.chrismorgan.info/u-plus/tree&quot;&gt;source code&lt;/a&gt; is on my Git server [Pity about that &lt;code&gt;u-plus&lt;/code&gt; in the URL. I wanted to do &lt;code&gt;U+&lt;/code&gt;, but gitweb wasn’t coping very well with plusses in the path, and I figured fixing that bug would take far too much effort, especially given the era that Perl code comes from. I’ve already &lt;a href=&quot;https://git.chrismorgan.info/gitweb/shortlog&quot;&gt;patched it enough&lt;/a&gt;, I should just write something from scratch.]; it may be easiest to view the entire thing as &lt;a href=&quot;https://git.chrismorgan.info/u-plus/patches/HEAD&quot;&gt;a patch&lt;/a&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;hr /&gt;
&lt;blockquote class=&quot;with-footer&quot;&gt;
&lt;p&gt;“All things are lawful for me,” but not all things are profitable. “All things are lawful for me,” but not all things build up.
&lt;footer&gt;&lt;cite&gt;Paul the Apostle, &lt;a class=bible-reference href=&quot;https://ebible.org/engwebpb/1CO10.htm#V23&quot;&gt;1 Corinthians 10:23&lt;/a&gt;&lt;/cite&gt;&lt;/footer&gt;
&lt;/blockquote&gt;

			&lt;aside class=trailer&gt;
		&lt;hr&gt;
		&lt;p&gt;Comments? Questions? Corrections? If you want to contact me about anything in this post, email me at &lt;a href=&quot;mailto:me@chrismorgan.info&quot;&gt;me@chrismorgan.info&lt;/a&gt;.
	&lt;/aside&gt;
		</content>
	</entry>
	<entry xml:base="https://chrismorgan.info/blog/rust-cfg_attr-mod-path/">
		<title type="html">&lt;code&gt;&lt;i&gt;#[cfg_attr(…, path = …)]&lt;/i&gt;&lt;/code&gt; for platform-specific module implementations</title>
		<published>2021-06-18T00:00:01+00:00</published>
		<updated>2021-06-18T00:00:01+00:00</updated>
		<link href="https://chrismorgan.info/blog/rust-cfg_attr-mod-path/" type="text/html"/>
		<id>https://chrismorgan.info/blog/rust-cfg_attr-mod-path/</id>
		<category scheme="https://chrismorgan.info/blog/tags/" term="rust" label="Rust" />
		<content type="html">
			&lt;p class=intro&gt;&lt;a href=/blog/rust-cfg_attr/&gt;I wrote about &lt;code&gt;&lt;i&gt;#[cfg_attr]&lt;/i&gt;&lt;/code&gt; and some interesting use cases for it&lt;/a&gt; some years ago. Time for another dose!
			&lt;p&gt;I have seen people write things like this often:&lt;/p&gt;
&lt;figure id=figure-1&gt;
&lt;pre&gt;&lt;code&gt;&lt;i&gt;#[cfg(unix)]&lt;/i&gt;
&lt;b&gt;mod&lt;/b&gt; unix;
&lt;i&gt;#[cfg(unix)]&lt;/i&gt;
&lt;b&gt;pub use&lt;/b&gt; self::unix::*;

&lt;i&gt;#[cfg(windows)]&lt;/i&gt;
&lt;b&gt;mod&lt;/b&gt; windows;
&lt;i&gt;#[cfg(windows)]&lt;/i&gt;
&lt;b&gt;pub use&lt;/b&gt; self::windows::*;

&lt;span class=unimportant&gt;… and commonly even more variations …&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;figcaption&gt;&lt;p&gt;&lt;strong&gt;Figure 1:&lt;/strong&gt; multiple &lt;code&gt;&lt;b&gt;mod&lt;/b&gt;&lt;/code&gt; and &lt;code&gt;&lt;b&gt;use&lt;/b&gt;&lt;/code&gt; statements in order to switch between platform‐specific implementations.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;This can get unwieldy.&lt;/p&gt;
&lt;p&gt;There are two features that you can combine to make this simpler and smaller:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg_attr-attribute&quot;&gt;The &lt;code&gt;&lt;i&gt;#[cfg_attr]&lt;/i&gt;&lt;/code&gt; attribute&lt;/a&gt;, which lets you apply an attribute conditionally, and&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://doc.rust-lang.org/reference/items/modules.html#the-path-attribute&quot;&gt;The &lt;code&gt;&lt;i&gt;#[path]&lt;/i&gt;&lt;/code&gt; attribute on &lt;code&gt;&lt;b&gt;mod&lt;/b&gt;&lt;/code&gt; statements&lt;/a&gt;, which lets you specify the path to the module rather than using Rust’s usual lookup (where for &lt;code&gt;&lt;b&gt;mod&lt;/b&gt; foo;&lt;/code&gt; it tries &lt;var&gt;foo.rs&lt;/var&gt; and &lt;var&gt;foo/mod.rs&lt;/var&gt;).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here’s how it goes when combined:&lt;/p&gt;
&lt;figure id=figure-2&gt;
&lt;pre&gt;&lt;code&gt;&lt;i&gt;#[cfg_attr(unix, path = &lt;span class=s&gt;&quot;unix.rs&quot;&lt;/span&gt;)]
#[cfg_attr(windows, path = &lt;span class=s&gt;&quot;windows/mod.rs&quot;&lt;/span&gt;)]&lt;/i&gt;
&lt;span class=unimportant&gt;… and perhaps even more variations …&lt;/span&gt;
&lt;b&gt;mod&lt;/b&gt; platform;
&lt;b&gt;pub use&lt;/b&gt; self::platform::*;&lt;/code&gt;&lt;/pre&gt;
&lt;figcaption&gt;&lt;p&gt;&lt;strong&gt;Figure 2:&lt;/strong&gt; just one &lt;code&gt;&lt;b&gt;mod&lt;/b&gt;&lt;/code&gt; statement decorated by multiple attributes in order to switch between implementations, and one &lt;code&gt;&lt;b&gt;use&lt;/b&gt;&lt;/code&gt; statement.&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;And so in this example, on Unix platforms it’ll load &lt;var&gt;unix.rs&lt;/var&gt; as the &lt;code&gt;platform&lt;/code&gt; module, while on Windows it’ll load &lt;var&gt;windows/mod.rs&lt;/var&gt; [FYI, if you went for &lt;var&gt;windows/mod.rs&lt;/var&gt; because &lt;code&gt;windows&lt;/code&gt; contained other modules inside it, know that from Rust 1.30 onwards you can actually have a file named &lt;var&gt;windows.rs&lt;/var&gt; beside that &lt;var&gt;windows/&lt;/var&gt; subdirectory, instead of it having to be &lt;var&gt;windows/mod.rs&lt;/var&gt;. &lt;a href=&quot;https://doc.rust-lang.org/reference/items/modules.html#module-source-filenames&quot;&gt;The Rust Reference even recommends switching to this new style&lt;/a&gt;, though I’m not sold on it.] as the &lt;code&gt;platform&lt;/code&gt; module, and so in either case it can subsequently do a reexport if desired.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;Mind you, for complex enough specifications, even the single mod version can still be messy:&lt;/p&gt;
&lt;figure id=figure-3&gt;
&lt;pre&gt;&lt;code&gt;&lt;i&gt;#[cfg_attr(
	all(
		target_arch = &lt;span class=s&gt;&quot;wasm32&quot;&lt;/span&gt;,
		any(target_os = &lt;span class=s&gt;&quot;emscripten&quot;&lt;/span&gt;, target_os = &lt;span class=s&gt;&quot;unknown&quot;&lt;/span&gt;),
	),
	path = &lt;span class=s&gt;&quot;wasm32/mod.rs&quot;&lt;/span&gt;
)]
#[cfg_attr(windows, path = &lt;span class=s&gt;&quot;windows/mod.rs&quot;&lt;/span&gt;)]
#[cfg_attr(
	not(any(
		all(
			target_arch = &lt;span class=s&gt;&quot;wasm32&quot;&lt;/span&gt;,
			any(target_os = &lt;span class=s&gt;&quot;emscripten&quot;&lt;/span&gt;, target_os = &lt;span class=s&gt;&quot;unknown&quot;&lt;/span&gt;),
		),
		windows,
	)),
	path = &lt;span class=s&gt;&lt;span class=s&gt;&quot;common/mod.rs&quot;&lt;/span&gt;&lt;/span&gt;
)]&lt;/i&gt;
&lt;b&gt;mod&lt;/b&gt; imp;&lt;/code&gt;&lt;/pre&gt;
&lt;figcaption&gt;&lt;p&gt;&lt;strong&gt;Figure 3:&lt;/strong&gt; a very slightly unwieldy&lt;soft-br&gt;&lt;/soft-br&gt; situation &lt;a href=https://github.com/dylni/os_str_bytes/blob/ddb6a791081e091f3b58c84b48aaa5ac96bb5cdb/src/lib.rs#L154-L172&gt;seen in os_str_bytes&lt;/a&gt;.
&lt;p class=sidenote&gt;(While thinking about os_str_bytes, I wonder what the chances are of ever convincing the Rust core and libs teams to make cross‐platform &lt;code&gt;OsStr&lt;/code&gt; → &lt;code&gt;[u8]&lt;/code&gt; and &lt;code&gt;OsString&lt;/code&gt; → &lt;code&gt;Vec&amp;lt;u8&gt;&lt;/code&gt; conversions (ideally plus checked and unchecked conversions for the other way). As it stands, &lt;code&gt;OsStr::to_str&lt;/code&gt; forces them to be roughly UTF-8 already, and the current implementation depends on compatibility, which I can’t honestly imagine ever changing, but the docs stubbornly insist on being mysterious, and the source code stubbornly insists of &lt;code&gt;OsStr&lt;/code&gt;, &lt;code&gt;OsString&lt;/code&gt;, &lt;code&gt;Path&lt;/code&gt; and &lt;code&gt;PathBuf&lt;/code&gt; that their “representation and layout are considered implementation details, are not documented and must not be relied upon”. But such musings as these don’t fit in a figure caption. I can already just &lt;em&gt;tell&lt;/em&gt; that half the comments about this article are going to be about this little side&lt;!-- tee hee --&gt; point.&lt;!-- … and yet I’m still leaving it in. 😀 --&gt;)&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;And truly they can get much worse than that; the worst cases I’ve seen might even be enough for me to reach for &lt;a href=https://lib.rs/crates/cfg-if&gt;cfg-if&lt;/a&gt; (which I am loath to do—​I reckon the significant majority of its uses are unwarranted) and separate &lt;code&gt;&lt;b&gt;mod&lt;/b&gt;&lt;/code&gt; statements, rather than using &lt;code&gt;&lt;i&gt;#[cfg_attr]&lt;/i&gt;&lt;/code&gt;.&lt;/p&gt;

			&lt;aside class=trailer&gt;
		&lt;hr&gt;
		&lt;p&gt;Comments? Questions? Corrections? If you want to contact me about anything in this post, email me at &lt;a href=&quot;mailto:me@chrismorgan.info&quot;&gt;me@chrismorgan.info&lt;/a&gt;.
	&lt;/aside&gt;
		</content>
	</entry>
	<entry xml:base="https://chrismorgan.info/blog/rust-artwork-owl/">
		<title type="html">&lt;code&gt;&amp;lt;_&amp;gt;::v::&amp;lt;_&amp;gt;&lt;/code&gt;</title>
		<published>2019-08-20T00:00:00+00:00</published>
		<updated>2019-08-20T00:00:00+00:00</updated>
		<link href="https://chrismorgan.info/blog/rust-artwork-owl/" type="text/html"/>
		<id>https://chrismorgan.info/blog/rust-artwork-owl/</id>
		<category scheme="https://chrismorgan.info/blog/tags/" term="rust" label="Rust" />
		<category scheme="https://chrismorgan.info/blog/tags/" term="fun" label="Fun" />
		<content type="html">
			&lt;p class=intro&gt;A fun little piece of Rust artwork.
			&lt;p&gt;Following on from &lt;a href=&quot;https://www.reddit.com/r/rust/comments/cpknjb/i_just_found_out_that_method_is_valid/&quot;&gt;someone’s discovery that &lt;code&gt;&amp;lt;_&amp;gt;::method()&lt;/code&gt; is valid&lt;/a&gt;, I got thinking about the left‐swimming and right‐swimming turbofishes, and decided that making an owl’s face out of it, &lt;code&gt;&amp;lt;_&amp;gt;::v::&amp;lt;_&amp;gt;&lt;/code&gt;, should be possible. Here’s what I came up with:&lt;/p&gt;
&lt;figure&gt;
&lt;figcaption&gt;&lt;p class=sidenote&gt;&lt;code&gt;&amp;lt;_&amp;gt;::v::&amp;lt;_&amp;gt;&lt;/code&gt;, the owl is sleeping soundly. &lt;a href=&quot;https://play.rust-lang.org/?version=stable&amp;amp;mode=debug&amp;amp;edition=2018&amp;amp;gist=69bbbfb1ee968ca9b3a32c48c2a73e6b&quot;&gt;Playground link&lt;/a&gt;&lt;/figcaption&gt;
&lt;pre&gt;&lt;code&gt;&lt;span class=unimportant&gt;&lt;b&gt;type&lt;/b&gt; O = &lt;b&gt;u8&lt;/b&gt;;

&lt;b&gt;trait&lt;/b&gt; V {
	&lt;b&gt;fn&lt;/b&gt; v&amp;lt;T: Default&amp;gt;() -&amp;gt; (T, Self);
}

&lt;b&gt;impl&lt;/b&gt; V &lt;b&gt;for&lt;/b&gt; O {
	&lt;b&gt;fn&lt;/b&gt; v&amp;lt;T: Default&amp;gt;() -&amp;gt; (T, Self) {
		(T::default(), &lt;span class=n&gt;0&lt;/span&gt;)
	}
}&lt;/span&gt;

&lt;b&gt;fn&lt;/b&gt; main() {
	&lt;b&gt;let&lt;/b&gt; owl = &lt;mark&gt;&amp;lt;_&amp;gt;::v::&amp;lt;_&amp;gt;&lt;/mark&gt;;

	&lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;&lt;b&gt;{:?}&lt;/b&gt;&quot;&lt;/span&gt;, owl() &lt;b&gt;as&lt;/b&gt; (O, O));
}&lt;/code&gt;&lt;/pre&gt;
&lt;/figure&gt;
&lt;figure class=output&gt;
&lt;figcaption&gt;&lt;p class=sidenote&gt;When you call the owl, it wakes up.&lt;/figcaption&gt;
&lt;pre&gt;&lt;samp&gt;(0, 0)&lt;/samp&gt;&lt;/pre&gt;
&lt;/figure&gt;
&lt;p&gt;(Fun fact: the artwork of the awakened owl happened by accident. For inference to work, I needed both the &lt;code&gt;Self&lt;/code&gt; type and one generic type to be in the return type, so &lt;code&gt;(Self, T)&lt;/code&gt; was the obvious type to use. Then, integers seemed the natural types to implement things on, and zero is the easiest number to use. And so I ended up with &lt;code&gt;(0, 0)&lt;/code&gt;, which I then realised was a picture in itself! The &lt;code&gt;O&lt;/code&gt; type alias is then just to mix things up a bit. Empty tuples would work as well, yielding &lt;code&gt;((), ())&lt;/code&gt;, but that didn’t feel quite as nice.)&lt;/p&gt;
&lt;h3 id=&quot;changelog&quot;&gt;Changelog&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;2019-08-20:&lt;/strong&gt; code simplified a tad &lt;a href=&quot;https://play.rust-lang.org/?version=stable&amp;amp;mode=debug&amp;amp;edition=2018&amp;amp;gist=eb6bd6c88d2da1a101c150aea5109b47&quot;&gt;from this&lt;/a&gt;, &lt;a href=&quot;https://www.reddit.com/r/rust/comments/csrr9m/v/exh333t/&quot;&gt;as demonstrated by /u/TROPAFLIGHT2&lt;/a&gt;. (Look at &lt;a href=&quot;https://www.reddit.com/r/rust/comments/csrr9m/v/exh7sa5/&quot;&gt;/u/ThomasdH’s variant&lt;/a&gt; too, it’s fun.)&lt;/li&gt;
&lt;/ul&gt;

			&lt;aside class=trailer&gt;
		&lt;hr&gt;
		&lt;p&gt;Comments? Questions? Corrections? If you want to contact me about anything in this post, email me at &lt;a href=&quot;mailto:me@chrismorgan.info&quot;&gt;me@chrismorgan.info&lt;/a&gt; or &lt;a href=https://www.reddit.com/r/rust/comments/csrr9m/v/&gt;discuss it on /r/rust&lt;/a&gt;.
	&lt;/aside&gt;
		</content>
	</entry>
	<entry xml:base="https://chrismorgan.info/blog/tween/">
		<title type="html">Tween: a middleware library experiment</title>
		<published>2016-06-01T00:00:00+00:00</published>
		<updated>2016-06-01T00:00:00+00:00</updated>
		<link href="https://chrismorgan.info/blog/tween/" type="text/html"/>
		<id>http://chrismorgan.info/blog/tween.html</id>
		<category scheme="https://chrismorgan.info/blog/tags/" term="web" label="Web" />
		<category scheme="https://chrismorgan.info/blog/tags/" term="rust" label="Rust" />
		<content type="html">
			&lt;p&gt;&lt;em&gt;This article is intended for people who are familiar with how web frameworks such as Django and Iron work; if you’re not familiar with such things you probably won’t get much out of this particular post. I’m not going to be explaining everything you might need to know.&lt;/em&gt;
			&lt;aside class=sidenote&gt;
&lt;h3&gt;Personal update&lt;soft-br&gt;&lt;/soft-br&gt; (for those interested)&lt;/h3&gt;
&lt;p&gt;I’m steadily getting back into R&amp;amp;D for a Rust web framework. I’ve been mostly off the radar for most of the last year, but I haven’t left Rust! I’ve been using it in my spare time, I just haven’t had much of that to dedicate to it, and I haven’t been doing much research that would be directly useful to others. Now at last I am, so here it is.&lt;/p&gt;
&lt;p&gt;After this, one of the next things I’m intending to tackle is a templating language inspired by ASP.NET Razor—​or Play Framework’s Twirl, which is much the same thing for Scala. I like statically typing all the things and am not fond of the handlebars and mustache templating engines for that reason, however much I like my own moustache. Lots of nice correctness and performance wins to be had. We can talk about that at some point, and if anyone wants to help out there, it’d be nice—​I haven’t worked with rustc much before, this will end up a fairly heavy-weight compiler plugin with lots of parsing and all to do. Should be fun.&lt;/p&gt;
&lt;p&gt;One of these days it’ll get to the stage where I finally start making the web framework that I came to Rust in the first place a few years back to make, rather than just making components for it. I’m hoping we’ll have a viable compile-to-JS story by then so I can proceed to experiment with an end-to-end Rust web app.&lt;/p&gt;
&lt;/aside&gt;
&lt;h2&gt;The existing state of middleware libraries in Rust&lt;/h2&gt;
&lt;p&gt;I’ll use &lt;a href=&quot;http://ironframework.io/doc/iron/middleware/&quot;&gt;&lt;code&gt;iron::middleware&lt;/code&gt;&lt;/a&gt; as an example of the current state of middleware in Rust:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The request and response objects have slots for adding data to them: &lt;code&gt;Request.extensions&lt;/code&gt; and &lt;code&gt;Response.extensions&lt;/code&gt;, which are &lt;code&gt;TypeMap&lt;/code&gt;s;&lt;/li&gt;
&lt;li&gt;Middleware can inject things into the request and/or response objects, or not, as the fancy takes you, and read from it to get data from previous middleware or the main handler in post-processing;&lt;/li&gt;
&lt;li&gt;There is no type-level dependency tracking, so you can’t say “such and such a piece of middleware must have been executed first”;&lt;/li&gt;
&lt;li&gt;Putting more data into the extension location requires allocating a new trait object each time, and accessing it is dynamic dispatch. Not &lt;em&gt;slow&lt;/em&gt;, especially compared with what a dynamic language would be doing, but not as fast as if you wrote the whole stack by hand.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;There are two main problems I wish to outline with all of this:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Confidence.&lt;/strong&gt; Lack of dependency tracking means that you end up with all sorts of places where you might end up panicking, and that it’s easy to make mistakes. Debugging can also be difficult, because your extension data is approximately opaque and so you can’t easily examine or print out its contents. (Admittedly, &lt;code&gt;Debug&lt;/code&gt; could be added as a bound in the &lt;code&gt;TypeMap&lt;/code&gt;, &lt;a href=https://github.com/chris-morgan/mopa&gt;MOPA-style&lt;/a&gt;, which would reduce its opacity to debugging.)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Performance.&lt;/strong&gt; Heap memory allocations and indirection everywhere. Imagine if you just had a simple struct containing all of this stuff, and so no heap allocations or complex lookups—​just straight field lookup. This turns something from being fairly fast to being &lt;em&gt;fast&lt;/em&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Encoding middleware dependencies into the type system is something that we (people such as myself and Jonathan Reem) tried two years back, but the Rust type system wasn’t &lt;em&gt;quite&lt;/em&gt; good enough back then: we collectively came to the conclusion that it just wasn’t possible, and probably wouldn’t be until the language gets HKT.&lt;/p&gt;
&lt;p&gt;This has annoyed me from time to time. Sure, they’re not necessarily &lt;em&gt;serious&lt;/em&gt; problems, but I do want to solve them.&lt;/p&gt;
&lt;p&gt;I came up with a new approach last week or the week before, and decided to have one last try. Well, that particular approach didn’t work (I think—​I’ve actually forgotten most of the details of what it was now), but a part of it did and it headed me in another direction and I wound up with something that got steadily more and more complex until it worked, and then I steadily pulled bits out of it until I wound up with a drastically simplified core that also worked. Then I just had to continue cutting the macros down (Quxxy helped me with the subcontexts one, thanks!) until the whole thing of a middleware chain was just one macro with only one extraneous piece of information per middleware in the chain (and when we get eager macro expansion, there will be &lt;em&gt;no&lt;/em&gt; extraneous information in the definitions).&lt;/p&gt;
&lt;h2&gt;The end result: Tween&lt;/h2&gt;
&lt;p&gt;The end result is a proof-of-concept middleware library for web frameworks. I’ve called it &lt;strong&gt;Tween&lt;/strong&gt;, because of a certain fondness I have for &lt;a href=https://docs.pylonsproject.org/projects/pyramid/en/latest/&gt;Pyramid&lt;/a&gt;, which calls ’em that. (Aside: using &lt;a href=https://docs.pylonsproject.org/projects/pyramid/en/latest/narr/muchadoabouttraversal.html&gt;traversal&lt;/a&gt; for URL routing instead of dispatch is really interesting. If you’re not familiar with it, you should try it purely to broaden your horizons. I don’t care whether you actually end up using it or not.)&lt;/p&gt;
&lt;p&gt;Tween’s key features are robustness (no cause for panicking) and performance (no need for heap memory), and static tween dependency declaration.&lt;/p&gt;
&lt;p&gt;The repository is a work in progress, a proof of concept. It has proven its concept, I believe.&lt;/p&gt;
&lt;h2&gt;What to do&lt;/h2&gt;
&lt;p&gt;&lt;svg viewBox=&quot;0 0 602 465&quot; stroke-linecap=round style=max-width:602px&gt;&lt;desc&gt;&lt;a href=https://gitlab.com/chris-morgan/tween/tree/master xlink:href=https://gitlab.com/chris-morgan/tween/tree/master&gt;Here is the code.&lt;/a&gt;&lt;/desc&gt;&lt;a href=https://gitlab.com/chris-morgan/tween/tree/master xlink:href=https://gitlab.com/chris-morgan/tween/tree/master&gt;&lt;title&gt;I can’t even remember why I thought this image was a good idea.&lt;!-- At least I didn’t animate it or make it *really* twinkly. Or even use any :hover recolouring. Count your blessings; name them one by one. --&gt;&lt;/title&gt;&lt;rect width=400 height=100 x=103 y=101 fill=#0f0 stroke=purple stroke-width=4 rx=5 /&gt;&lt;text x=298 y=167 font-size=40 letter-spacing=0 text-anchor=middle fill=#00f&gt;CODE IS HERE!&lt;/text&gt;&lt;/a&gt;&lt;path fill=none stroke=currentColor stroke-width=3 d=M332,464l-40-95-45,95m45-203v108m-57-168l57,101,59-101 /&gt;&lt;circle cx=292 cy=242 r=19 fill=none stroke=currentColor stroke-width=3 /&gt;&lt;text x=234 y=-285 transform=rotate(90) font-size=20 fill=currentColor font-family=concourse,sans-serif&gt;:D&lt;/text&gt;&lt;path fill=none stroke=#ff0 stroke-width=10 d=M174,19c-3,21,5,41,14,60M11,142c12-3,22,8,34,10m41,140c2-15,20-21,25-36m334,7c-2,30,21,54,31,82m84-172c12,1,23,8,36,10M394,83c-1-29,23-54,39-77 /&gt;&lt;path fill=none stroke=red stroke-width=10 d=M292,31c-1,17,1,34,1,52M41,61c6,5,17,8,19,18M6,231c12-8,27-13,38-23m144,62c-10,7-21,14-31,23m225-19v35m144-51c7,13,27,15,29,32M495,80c17-9,30-25,49-30 /&gt;&lt;/svg&gt;&lt;/p&gt;
&lt;p&gt;An explanation of how it works is there in that README.&lt;/p&gt;
&lt;p&gt;This is a proof of concept. For the sake of performance it plays fast and loose with memory safety internally, and although I believe it handles everything appropriately even in case of panicking, it’d be good to have review by others. I could easily have missed something. There could also be better ways of doing some parts of it.&lt;/p&gt;
&lt;p&gt;If you want to help me by giving feedback—​good things and bad things about the design, issues I haven’t thought of, ideas of ways of improving it, &lt;i&gt;&amp;amp;c.&lt;/i&gt;—​please &lt;a href=https://www.reddit.com/r/rust/https://chrismorgan.info/blog/tween.html&gt;comment in /r/rust&lt;/a&gt;, &lt;a href=https://gitlab.com/chris-morgan/tween/issues&gt;file an issue in the tween repository&lt;/a&gt;, or &lt;a href=mailto:me@chrismorgan.info&gt;drop me a line at me@chrismorgan.info&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;And no, I haven’t written any benchmarks yet.&lt;/p&gt;

			&lt;aside class=trailer&gt;
		&lt;hr&gt;
		&lt;p&gt;Comments? Questions? Corrections? If you want to contact me about anything in this post, email me at &lt;a href=&quot;mailto:me@chrismorgan.info&quot;&gt;me@chrismorgan.info&lt;/a&gt;.
	&lt;/aside&gt;
		</content>
	</entry>
	<entry xml:base="https://chrismorgan.info/blog/rust-ownership-the-hard-way/">
		<title type="html">Rust ownership, the hard way</title>
		<published>2015-05-12T00:00:00+00:00</published>
		<updated>2021-08-04T00:00:00+00:00</updated>
		<link href="https://chrismorgan.info/blog/rust-ownership-the-hard-way/" type="text/html"/>
		<id>http://chrismorgan.info/blog/rust-ownership-the-hard-way.html</id>
		<category scheme="https://chrismorgan.info/blog/tags/" term="rust" label="Rust" />
		<content type="html">
			&lt;p class=intro&gt;In order to truly understand Rust, one needs to understand its crucial differentiating feature: ownership. Let’s go through it in detail the hard way.
			&lt;p&gt;This article is an introduction to Rust’s concept of ownership. It’s designed for someone who is already a programmer but who is not especially familiar (maybe even not at all familiar) with Rust. It doesn’t attempt to explain all the concepts it deals with, but for the most part it should be clear enough. If you’re a beginner you may also find that you don’t understand various parts of it; in such a case, you might like to hold the article while you go and learn more about them elsewhere; you’ll find more value in coming back to this article after.
&lt;p&gt;This concept of ownership is the pivotal part of Rust; it’s the part that makes its combination of efficiency and safety possible. While the rest of Rust is pretty similar to what you’ll find in mainstream languages [OK, so pattern matching and algebraic data types aren’t widespread in C‐style languages, but they’re conceptually simple.], these concepts of ownership and lifetimes are different from anything in any mainstream language, so it’s likely to be the part that you’ll spend the longest trying to grok; if you don’t give up but persist, then when it all clicks, working in Rust will be a joy, and you’ll have unlocked a marvellous ability to reason about code. You’ll also probably wish you could transplant a lot of the aspects of Rust’s ownership model to other languages you deal with. [Seriously. The ownership model makes reasoning about many things &lt;em&gt;so&lt;/em&gt; much easier, and I really &lt;em&gt;do&lt;/em&gt; miss it when working in other languages.]
&lt;p&gt;This article deals with the concepts and theory of ownership and lifetimes; it doesn’t provide much in the way of practical usage examples; those you can find elsewhere. But it does explain all the rules that go to make Rust’s ownership model what it is. (It &lt;em&gt;is&lt;/em&gt; called “the hard way” for a reason.)
&lt;p&gt;Well, on with the first of our four rules:
&lt;h2 id=rule-one&gt;&lt;ol&gt;&lt;li value=1&gt;Each object can be used exactly once. When you use an object it is moved to the new location and is no longer usable in the old.&lt;/ol&gt;&lt;/h2&gt;
&lt;p&gt;&lt;a href=#exceptions-to-single-use&gt;Later on&lt;/a&gt; we’ll deal with a couple of features that make this model more palatable, but for now we’ll skip them, considering it at the most basic level.
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;struct&lt;/b&gt; A {}

&lt;b&gt;fn&lt;/b&gt; main() {
    &lt;b&gt;let&lt;/b&gt; a = A {};
    &lt;b&gt;let&lt;/b&gt; b = a;
    &lt;b&gt;let&lt;/b&gt; c = a;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;!-- Output from rustc 1.54.0; omitted “unused variable” warnings, “; 2 warnings emitted” on the last line, and “For more information about this error, try `rustc --explain E0382`.” at the very end. --&gt;
&lt;figure class=compiler-output&gt;&lt;pre&gt;&lt;samp&gt;&lt;b&gt;&lt;span class=ansi-red&gt;error[E0382]&lt;/span&gt;: use of moved value: `a`&lt;/b&gt;
&lt;b class=ansi-blue&gt; --&amp;gt;&lt;/b&gt; &amp;lt;anon&amp;gt;:6:13
&lt;b class=ansi-blue&gt;  |&lt;/b&gt;
&lt;b class=ansi-blue&gt;4 | &lt;/b&gt;    let a = A {};
&lt;b class=ansi-blue&gt;  |         - move occurs because `a` has type `A`, which does not implement the `Copy` trait&lt;/b&gt;
&lt;b class=ansi-blue&gt;5 | &lt;/b&gt;    let b = a;
&lt;b class=ansi-blue&gt;  |         - value moved here&lt;/b&gt;
&lt;b class=ansi-blue&gt;6 | &lt;/b&gt;    let c = a;
&lt;b class=ansi-blue&gt;  | &lt;/b&gt;        &lt;b class=ansi-red&gt;^ value used here after move&lt;/b&gt;

&lt;b&gt;&lt;span class=ansi-red&gt;error&lt;/span&gt;: aborting due to previous error&lt;/b&gt;&lt;/samp&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;The &lt;code&gt;A&lt;/code&gt; instance placed in the slot &lt;code&gt;a&lt;/code&gt; is moved to &lt;code&gt;b&lt;/code&gt;, rendering &lt;code&gt;a&lt;/code&gt; unusable.
&lt;h2&gt;&lt;ol&gt;&lt;li value=2&gt;When an object passes out of scope, it is destroyed and is no longer usable.&lt;/ol&gt;&lt;/h2&gt;
&lt;p&gt;&lt;em&gt;Blocks&lt;/em&gt;, delimited by curly braces [But not to be confused with struct declarations like &lt;code&gt;&lt;b&gt;struct&lt;/b&gt; A {}&lt;/code&gt; and struct literals like &lt;code&gt;A {}&lt;/code&gt;, as seen in this next example.], introduce a new level of scope, and anything declared inside a block (e.g. the binding &lt;code&gt;x&lt;/code&gt; in &lt;code&gt;&lt;b&gt;let&lt;/b&gt; x = y;&lt;/code&gt;) will live until the end of that block. [This was strictly true when I first wrote this article, but &lt;em&gt;non‐lexical lifetimes&lt;/em&gt; landed in Rust 1.31 in 2018: in certain situations objects can now be destroyed before the end of their containing lexical scope; but I don’t think this is the right article to delve into detail about it. Suffice it to say that although it makes Rust conceptutally more complex, it makes it do what you want (rather than producing a compiler error) more of the time.]
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;struct&lt;/b&gt; A {}

&lt;b&gt;fn&lt;/b&gt; main() {
    {
        &lt;b&gt;let&lt;/b&gt; a = A {};
    }
    &lt;b&gt;let&lt;/b&gt; b = a;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;This example won’t work, because &lt;code&gt;a&lt;/code&gt; has fallen out of scope and been destroyed by the time we try to assign it to &lt;code&gt;b&lt;/code&gt;:
&lt;!-- Output from rustc 1.54.0. Omitted “For more information about this error, try `rustc --explain E0425`.” at the end. --&gt;
&lt;figure class=compiler-output&gt;&lt;pre&gt;&lt;samp&gt;&lt;b&gt;&lt;span class=ansi-red&gt;error[E0425]&lt;/span&gt;: cannot find value `a` in this scope&lt;/b&gt;
&lt;b class=ansi-blue&gt; --&amp;gt;&lt;/b&gt; &amp;lt;anon&amp;gt;:7:13
&lt;b class=ansi-blue&gt;  |&lt;/b&gt;
&lt;b class=ansi-blue&gt;7 | &lt;/b&gt;    let b = a;
&lt;b class=ansi-blue&gt;  | &lt;/b&gt;            &lt;b class=ansi-red&gt;^ not found in this scope&lt;/b&gt;

&lt;b&gt;&lt;span class=ansi-red&gt;error&lt;/span&gt;: aborting due to previous error&lt;/b&gt;&lt;/samp&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;aside class=sidenote&gt;
	&lt;p&gt;There are seven ways of introducing variable bindings; all use patterns, and all but &lt;code&gt;&lt;b&gt;let&lt;/b&gt;&lt;/code&gt; introduce a new level of scope. They are: &lt;code&gt;&lt;b&gt;let&lt;/b&gt;&lt;/code&gt;; match branches; &lt;code&gt;&lt;b&gt;for&lt;/b&gt;&lt;/code&gt;; &lt;code&gt;&lt;b&gt;if let&lt;/b&gt;&lt;/code&gt;; &lt;code&gt;&lt;b&gt;while let&lt;/b&gt;&lt;/code&gt;; function arguments; and closure arguments.
&lt;/aside&gt;
&lt;p&gt;When an object passes out of scope and is destroyed, if the type implements &lt;a href=https://doc.rust-lang.org/std/ops/trait.Drop.html&gt;&lt;code&gt;Drop&lt;/code&gt;&lt;/a&gt;, that destructor will be run. I won’t get into the details of destructors here. Types like &lt;code&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;T&lt;/code&gt; and &lt;code&gt;&lt;b&gt;&amp;amp;mut &lt;/b&gt;T&lt;/code&gt; (immutable and mutable references) do not have destructors.
&lt;h2&gt;&lt;ol&gt;&lt;li value=3&gt;Blocks can produce a value which goes up one level of scope.&lt;/ol&gt;&lt;/h2&gt;
&lt;p&gt;As a language feature, this is typically known as &lt;em&gt;expression orientation&lt;/em&gt;, as distinct from &lt;em&gt;statement orientation&lt;/em&gt;. It’s a fairly simple concept and will seem perfectly natural to users of languages like Ruby, though to users of languages like C++ and Python it may seem a little odd. (I came originally from a Python background; at first I thought it a gimmick useful only for skipping the word &lt;code&gt;&lt;b&gt;return&lt;/b&gt;&lt;/code&gt; on the last statement of a function, but I rapidly discovered it isn’t a gimmick at all; it’s a very useful feature, for all that it wouldn’t suit a language like Python.)
&lt;p&gt;The main rule is simple: the last expression in a block is the value that the block produces. (A block is thus an expression too.) There are a couple of other rules to deal with the corner cases:
&lt;aside class=sidenote&gt;
	&lt;p&gt;People with some Rust experience may be familiar with the explanation of an implied &lt;code&gt;()&lt;/code&gt; after a semicolon at the end of a block; this is not accurate, &lt;a href=&quot;https://play.rust-lang.org/?code=fn foo() -&gt; i32 { return 0; () }&quot;&gt;as this type checking error shows&lt;/a&gt;. The reachability check is important as it allows things like a &lt;code&gt;&lt;b&gt;return&lt;/b&gt;&lt;/code&gt; statement at the end of a function that returns something other than unit (even though that &lt;em&gt;specific&lt;/em&gt; thing is considered bad style).
&lt;/aside&gt;
&lt;ul&gt;
    &lt;li&gt;&lt;p&gt;An empty block produces &lt;code&gt;()&lt;/code&gt; (&lt;em&gt;unit&lt;/em&gt;).
	&lt;li&gt;&lt;p&gt;If a block’s contents ends with a semicolon and the end of the block is reachable, the block produces &lt;code&gt;()&lt;/code&gt;.
&lt;/ul&gt;
&lt;p&gt;Here’s a simple example:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;let&lt;/b&gt; a = {
    &lt;i class=c&gt;// … do anything we like …&lt;/i&gt;
    &lt;span class=n&gt;1&lt;/span&gt;
};
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;Here, &lt;code&gt;a&lt;/code&gt; ends up storing the value &lt;code class=n&gt;1&lt;/code&gt;. Given these rules, you can see that putting braces around an expression changes nothing, for at each added level the block contains only a single expression, which is then its own value. Hence, &lt;code&gt;&lt;b&gt;let&lt;/b&gt; a = { { { { &lt;span class=n&gt;1&lt;/span&gt; } } } };&lt;/code&gt; and &lt;code&gt;&lt;b&gt;let&lt;/b&gt; a = &lt;span class=n&gt;1&lt;/span&gt;;&lt;/code&gt; are equivalent. [They’re actually not &lt;em&gt;quite&lt;/em&gt; equivalent in general, for a block expression is an &lt;em&gt;rvalue&lt;/em&gt;; thus &lt;code&gt;string[..].is_empty()&lt;/code&gt; works, while &lt;code&gt;{ string[..] }.is_empty()&lt;/code&gt; doesn’t.]
&lt;p&gt;In languages without this feature, the only type of block that produces a value (if you’ll allow my sloppy terminology here) is a function; there, they have the &lt;code&gt;&lt;b&gt;return&lt;/b&gt;&lt;/code&gt; keyword to fill in this blank. (Rust also has the &lt;code&gt;&lt;b&gt;return&lt;/b&gt;&lt;/code&gt; keyword to make early return more convenient, but the language would work fine without it—​it’d just be harder to write some sorts of code.&lt;!-- 2021-08-04: I’m not certain if this (that `return` could be removed without reducing the expressiveness of functions) is actually true at present; I *think* it is since the advent of non‐lexical lifetimes (1.31), but I’m not certain. The Polonius borrow checker may affect the situation a bit too, though whether for better or worse I don’t know. Loops are the main fiddly bit. --&gt;)
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;fn&lt;/b&gt; foo_the_c_way() -&gt; &lt;b&gt;i32&lt;/b&gt; {
    &lt;b&gt;return&lt;/b&gt; &lt;span class=n&gt;1&lt;/span&gt;;
}

&lt;b&gt;fn&lt;/b&gt; foo_the_rust_way() -&gt; &lt;b&gt;i32&lt;/b&gt; {
    &lt;span class=n&gt;1&lt;/span&gt;
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;Because of this paradigm of expression orientation, the concept of special &lt;em&gt;ternary expressions&lt;/em&gt; [&lt;code&gt;condition ? a : b&lt;/code&gt; in most languages;&lt;soft-br&gt;&lt;/soft-br&gt; &lt;code&gt;a &lt;b&gt;if&lt;/b&gt; condition &lt;b&gt;else&lt;/b&gt; b&lt;/code&gt; in Python.] is not necessary in Rust, for an &lt;code&gt;&lt;b&gt;if&lt;/b&gt;&lt;/code&gt; expression can do the job just fine:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;let&lt;/b&gt; x = &lt;b&gt;if&lt;/b&gt; a { b } &lt;b&gt;else&lt;/b&gt; { c };

&lt;b&gt;let&lt;/b&gt; x = &lt;b&gt;if&lt;/b&gt; a {
    &lt;i class=c&gt;// … do things …&lt;/i&gt;
    b
} &lt;b&gt;else&lt;/b&gt; {
    &lt;i class=c&gt;// … do things …&lt;/i&gt;
    c
};
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;!-- A related bonus of not doing ternary expressions is that ? was left unused, and so from Rust 1.14 we got the ? operator for early return (https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator) without causing confusion or potential parser trouble. --&gt;
&lt;h2&gt;&lt;ol&gt;&lt;li value=4&gt;All objects have a lifetime which constrains which scopes they may be moved out of.&lt;/ol&gt;&lt;/h2&gt;
&lt;p&gt;Now we’re getting into the harder stuff, the biggest thing that’s unusual about Rust: lifetimes. Syntactically, a lifetime in Rust is any identifier with the prefix of a single quotation mark, e.g. &lt;code&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&lt;/code&gt;. Any name will do for a lifetime, but there is one special lifetime, &lt;code&gt;&lt;b class=s&gt;&lt;i&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&lt;/code&gt;, which means that an object contains no non‐static references. Most of the primitive types (&lt;code&gt;&lt;b&gt;i32&lt;/b&gt;&lt;/code&gt;, &lt;code&gt;&lt;b&gt;bool&lt;/b&gt;&lt;/code&gt;, &lt;code&gt;&lt;b&gt;str&lt;/b&gt;&lt;/code&gt;, &lt;code&gt;[T]&lt;/code&gt;, &lt;i&gt;&amp;amp;c.&lt;/i&gt;) are static; those that are not are:
&lt;ul&gt;
	&lt;li&gt;Arrays (&lt;code&gt;[T; n]&lt;/code&gt;) and slices (&lt;code&gt;[T]&lt;/code&gt;) of non‐static types;
	&lt;li&gt;Tuples with non‐static members;
	&lt;li&gt;Non‐static references, &lt;i&gt;viz.&lt;/i&gt; any &lt;code&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;T&lt;/code&gt; or &lt;code&gt;&lt;b&gt;&amp;amp;mut&lt;/b&gt; T&lt;/code&gt; except &lt;code&gt;&lt;b&gt;&amp;amp;&lt;i class=s&gt;&apos;static&lt;/i&gt;&lt;/b&gt; T&lt;/code&gt; and &lt;code&gt;&lt;b&gt;&amp;amp;&lt;i class=s&gt;&apos;static&lt;/i&gt; mut&lt;/b&gt; T&lt;/code&gt;.
&lt;/ul&gt;
&lt;aside class=sidenote&gt;
	&lt;h3&gt;Conventions&lt;/h3&gt;
	&lt;p&gt;Just as there is a widespread convention for generic type parameters with no special significance to have names following the pattern &lt;code&gt;T&lt;/code&gt;, &lt;code&gt;U&lt;/code&gt;, &lt;code&gt;V&lt;/code&gt;, &lt;i&gt;&amp;amp;c.&lt;/i&gt;, there is a convention for generic lifetime parameters in Rust to follow the pattern &lt;code&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&lt;/code&gt;, &lt;code&gt;&lt;i class=s&gt;&apos;b&lt;/i&gt;&lt;/code&gt;, &lt;code&gt;&lt;i class=s&gt;&apos;c&lt;/i&gt;&lt;/code&gt;, &lt;i&gt;&amp;amp;c.&lt;/i&gt;
	&lt;p&gt;It’s also common to give them more meaningful letters or snake_case names; for example, where a key‐value pair might be &lt;code&gt;Pair&amp;lt;K, V&gt;&lt;/code&gt;, if you needed lifetime parameters corresponding to each of them individually (this is occasionally useful, though in a case like this they’ll typically have the same lifetime) you might go for &lt;code&gt;&lt;i class=s&gt;&apos;k&lt;/i&gt;&lt;/code&gt; and &lt;code&gt;&lt;i class=s&gt;&apos;v&lt;/i&gt;&lt;/code&gt;.
&lt;/aside&gt;
&lt;h3&gt;Lifetime positions in types&lt;/h3&gt;
&lt;p&gt;There are four places where a lifetime can appear in a &lt;em&gt;type&lt;/em&gt;:
&lt;ul&gt;
	&lt;li&gt;&lt;code&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; Type&lt;/code&gt;: the lifetime of an immutable reference;
	&lt;li&gt;&lt;code&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; &lt;b&gt;mut&lt;/b&gt; Type&lt;/code&gt;: the lifetime of a mutable reference;
	&lt;li&gt;&lt;code&gt;Type&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&gt;&lt;/code&gt;: a generic lifetime parameter on a type;
	&lt;li&gt;&lt;code&gt;&lt;b&gt;dyn&lt;/b&gt; Trait + &lt;i class=s&gt;&apos;a&lt;/i&gt;&lt;/code&gt; [Before Rust 1.27, this was spelled without the &lt;code&gt;&lt;b&gt;dyn&lt;/b&gt;&lt;/code&gt; keyword, called a &lt;em&gt;&lt;a href=https://doc.rust-lang.org/rustc/lints/listing/warn-by-default.html#bare-trait-objects&gt;bare trait object&lt;/a&gt;&lt;/em&gt;; that syntax was subsequently deprecated and is &lt;a href=https://github.com/rust-lang/rust/pull/83213&gt;removed altogether in the 2021 edition&lt;/a&gt;.]: a trait object’s lifetime, as with generic bounds (dealt with below).
&lt;/ul&gt;
&lt;p&gt;The first two are, I believe, fairly obvious; it’s clearly unsafe to have a reference to an object that has been freed. (By baking this into the language, we avoid the problem of &lt;em&gt;dangling pointers&lt;/em&gt; that languages like C have.)
&lt;p&gt;The third is much the same, as all generic lifetime parameters will, somewhere down the way, be of one of the other types, and so it’s just a way of passing that constraint through the types, like this:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;struct&lt;/b&gt; Ref&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;, T: &lt;i class=s&gt;&apos;a&lt;/i&gt;&gt;(&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; T);&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;As you can see, this &lt;code&gt;Ref&lt;/code&gt; type is basically just a wrapper around an immutable reference; as the contained field is of that lifetime, clearly the containing structure may not live any longer than it and so it must have that lifetime also. (The &lt;code&gt;T: &lt;i class=s&gt;&apos;a&lt;/i&gt;&lt;/code&gt; part is a type bound, saying that the generic type &lt;code&gt;T&lt;/code&gt; must live for at least &lt;code&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&lt;/code&gt;; without this it would not work, for as already discussed it clearly wouldn’t make sense to have a reference living longer than the object it refers to.)
&lt;p&gt;The fourth and final of these (&lt;code&gt;&lt;b&gt;dyn&lt;/b&gt; Trait + &lt;i class=s&gt;&apos;a&lt;/i&gt;&lt;/code&gt;) is, I think, the most interesting, and it’s worth spending a short time on trait objects, because the way in which they fit into this arrangement is &lt;em&gt;slightly&lt;/em&gt; different from elsewhere.
&lt;p&gt;Trait objects are Rust’s form of safe and convenient &lt;em&gt;dynamic dispatch&lt;/em&gt; (that’s what the &lt;code&gt;&lt;b&gt;dyn&lt;/b&gt;&lt;/code&gt; stands for); they allow you to store arbitrary types that satisfy a trait in the one type. Because of the potential difference in size of the types implementing a trait, trait objects are only usable through a reference of some form; the owned form is thus &lt;code&gt;&lt;b&gt;Box&lt;/b&gt;&amp;lt;&lt;b&gt;dyn&lt;/b&gt; Trait&gt;&lt;/code&gt;, and for references you can have &lt;code&gt;&lt;b&gt;&amp;amp;dyn &lt;/b&gt;Trait&lt;/code&gt; and &lt;code&gt;&lt;b&gt;&amp;amp;mut dyn&lt;/b&gt; Trait&lt;/code&gt;. This is a very brief and wholly lacking explanation of trait objects; you can find documentation of them elsewhere; a detailed explanation is out of scope&lt;!-- ha! --&gt; for this article.
&lt;p&gt;As stated, a trait object may be of a variety of different types; what, then, is the lifetime of a trait object? The answer is that we must specify it, like &lt;code&gt;&lt;b&gt;Box&lt;/b&gt;&amp;lt;&lt;b&gt;dyn&lt;/b&gt; Trait + &lt;b class=s&gt;&lt;i&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&gt;&lt;/code&gt;, indicating that the contained object must be &lt;code&gt;&lt;b class=s&gt;&lt;i&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&lt;/code&gt;, and &lt;code&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; (&lt;b&gt;dyn&lt;/b&gt; Trait + &lt;i class=s&gt;&apos;a&lt;/i&gt;)&lt;/code&gt;, indicating that the contained object’s lifetime must be at least &lt;code&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&lt;/code&gt;. Now as it happens, some of these common cases like &lt;code&gt;+ &lt;b class=s&gt;&lt;i&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&lt;/code&gt; on a boxed trait object and the duplication of the &lt;code&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&lt;/code&gt; in the reference are taken care of as default trait bounds—​&lt;code&gt;&lt;b&gt;Box&lt;/b&gt;&amp;lt;&lt;b&gt;dyn&lt;/b&gt; Trait&gt;&lt;/code&gt; is normally equivalent to &lt;code&gt;&lt;b&gt;Box&lt;/b&gt;&amp;lt;&lt;b&gt;dyn&lt;/b&gt; Trait + &lt;b class=s&gt;&lt;i&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&gt;&lt;/code&gt; and &lt;code&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; &lt;b&gt;dyn&lt;/b&gt; Trait&lt;/code&gt; to &lt;code&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; (&lt;b&gt;dyn&lt;/b&gt; Trait + &lt;i class=s&gt;&apos;a&lt;/i&gt;)&lt;/code&gt;. &lt;a href=https://github.com/rust-lang/rfcs/blob/master/text/0599-default-object-bound.md&gt;RFC 599, on default object bounds&lt;/a&gt;, treats the current rules on this subject more precisely. [RFC 599 was written before the invention of the &lt;code&gt;&lt;b&gt;dyn&lt;/b&gt;&lt;/code&gt; keyword, so you’ll see the old‐style &lt;a href=https://doc.rust-lang.org/rustc/lints/listing/warn-by-default.html#bare-trait-objects&gt;bare trait object&lt;/a&gt; syntax in that document.]
&lt;p&gt;(Note that just as the lifetime on a trait object can be omitted due to &lt;em&gt;default object bounds&lt;/em&gt;, lifetimes on the other three cases can also often be omitted; the current rules of lifetime elision are covered in &lt;a href=https://github.com/rust-lang/rfcs/blob/master/text/0141-lifetime-elision.md&gt;RFC 141&lt;/a&gt;.)
&lt;p&gt;But still you may wonder: why do trait object need a lifetime? I think it’s easiest to just give an example of something that would be bad if it were allowed to compile (&lt;a href=&quot;https://play.rust-lang.org/?code=fn main() %7B%0A    let trait_object: %26dyn AsRef&lt;str&gt; %3D %7B%0A        let string %3D %22I am a String%22.to_owned();%0A        %26string%0A    };%0A    println!(%22The string is {:?}%22%2C trait_object.as_ref());%0A}&quot;&gt;which it isn’t&lt;/a&gt;):
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;fn&lt;/b&gt; main() {
    &lt;b&gt;let&lt;/b&gt; trait_object: &lt;b&gt;&amp;amp;dyn&lt;/b&gt; AsRef&amp;lt;&lt;b&gt;str&lt;/b&gt;&amp;gt; = {
        &lt;b&gt;let&lt;/b&gt; string = &lt;span class=s&gt;&quot;I am a String&quot;&lt;/span&gt;.to_owned();
        &lt;b&gt;&amp;amp;&lt;/b&gt;string
    };
    &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;The string is &lt;b&gt;{:?}&lt;/b&gt;&quot;&lt;/span&gt;, trait_object.as_ref());
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;By the time execution gets to the &lt;code&gt;&lt;i&gt;println!&lt;/i&gt;&lt;/code&gt; statement, &lt;code&gt;string&lt;/code&gt; has been freed, so if this were allowed to compile, &lt;code&gt;trait_object&lt;/code&gt;, which points to the contents of &lt;code&gt;string&lt;/code&gt;, would also thus be pointing to freed memory, which is emphatically a Bad Thing™. To maintain memory safety, the boxed trait object cannot live longer than the string it contains a reference to.
&lt;h3&gt;Lifetime positions in generic bounds&lt;/h3&gt;
&lt;p&gt;As shown very basically above, a lifetime can also appear in &lt;em&gt;type parameter bounds&lt;/em&gt; and &lt;em&gt;lifetime parameter bounds&lt;/em&gt;. Here are some more examples:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;struct&lt;/b&gt; Ref&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;, T: SomeTrait + AnotherTrait + &lt;mark&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&lt;/mark&gt;&amp;gt;(&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; T);

&lt;i class=c&gt;// Suppose we have something that is reading values from a buffer and storing&lt;/i&gt;
&lt;i class=c&gt;// the decoded values, which still contain references to parts of the original&lt;/i&gt;
&lt;i class=c&gt;// buffer, into a vector. For maximal generality, we have *two* lifetimes,&lt;/i&gt;
&lt;i class=c&gt;// though normally one would suffice (this is a poor example since it doesn’t&lt;/i&gt;
&lt;i class=c&gt;// benefit from taking two lifetimes). The reference to the vector must not&lt;/i&gt;
&lt;i class=c&gt;// outlive the vector and all its items, which must not outlive the buffer.&lt;/i&gt;
&lt;b&gt;struct&lt;/b&gt; DecodeResult&amp;lt;&lt;i class=s&gt;&apos;buf&lt;/i&gt;: &lt;mark&gt;&lt;i class=s&gt;&apos;decoded&lt;/i&gt;&lt;/mark&gt;, &lt;i class=s&gt;&apos;decoded&lt;/i&gt;, T: &lt;mark&gt;&lt;i class=s&gt;&apos;buf&lt;/i&gt;&lt;/mark&gt;&amp;gt; {
	buffer: &lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;buf&lt;/i&gt; [&lt;b&gt;u8&lt;/b&gt;],
	decoded: &lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;decoded&lt;/i&gt; &lt;b&gt;mut&lt;/b&gt; Vec&amp;lt;T&gt;,
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;By type parameter bounds we mean the &lt;code&gt;T: &lt;i class=s&gt;&apos;buf&lt;/i&gt;&lt;/code&gt;, stating that the lifetime of the type &lt;code&gt;T&lt;/code&gt; must be at least &lt;code&gt;&lt;i class=s&gt;&apos;buf&lt;/i&gt;&lt;/code&gt; (it must live at least as long as the buffer).
&lt;p&gt;By lifetime parameter bounds we mean the &lt;code&gt;&lt;i class=s&gt;&apos;buf&lt;/i&gt;: &lt;i class=s&gt;&apos;decoded&lt;/i&gt;&lt;/code&gt;, stating that the lifetime &lt;code&gt;&lt;i class=s&gt;&apos;buf&lt;/i&gt;&lt;/code&gt; must be at least as long as (must satisfy the constraint) &lt;code&gt;&lt;i class=s&gt;&apos;decoded&lt;/i&gt;&lt;/code&gt;. This is extremely rare and is typically only of any use when &lt;a href=https://doc.rust-lang.org/nomicon/subtyping.html#variance&gt;subtyping and variance gets involved&lt;/a&gt;.
&lt;p&gt;Really, these sorts of bounds are very similar to the trait object bounds: because generics can be of arbitrary types, you will often need to stipulate a minimal lifetime in order to work with a type. In the &lt;code&gt;DecodeResult&lt;/code&gt; example above, &lt;code&gt;T&lt;/code&gt;’s lifetime must be constrained to be at least &lt;code&gt;&lt;i class=s&gt;&apos;decoded&lt;/i&gt;&lt;/code&gt;, or else the reference in the &lt;code&gt;decoded&lt;/code&gt; field would not be valid. Rust could infer this sort of thing, but it would lead to surprises in various areas, so it refrains from the attempt.
&lt;h2 id=exceptions-to-single-use&gt;Exceptions to “each object can be used exactly once”&lt;/h2&gt;
&lt;p&gt;There; we’ve covered the four basic rules. There remains still one point to explain. Earlier on I posited the simple rule that each object can be used exactly once; as I also said, this isn’t actually universally true. There are two exceptions to this rule.
&lt;h3&gt;&lt;ol&gt;&lt;li&gt;Copy and move semantics&lt;/li&gt;&lt;/h3&gt;
&lt;p&gt;Objects of types with &lt;em&gt;move semantics&lt;/em&gt; can only be used once, but this is not true of types with &lt;em&gt;copy semantics&lt;/em&gt;.
&lt;p&gt;An object has &lt;em&gt;copy semantics&lt;/em&gt; if it implements &lt;a href=https://doc.rust-lang.org/std/marker/trait.Copy.html&gt;&lt;code&gt;Copy&lt;/code&gt;&lt;/a&gt;. This means that a value of that type can be duplicated simply by copying the bytes of memory. &lt;code&gt;&lt;b&gt;i32&lt;/b&gt;&lt;/code&gt;, for example, is &lt;code&gt;Copy&lt;/code&gt; because it’s just an arbitrary four bytes of data, entirely self‐contained, while &lt;code&gt;&lt;b&gt;Box&lt;/b&gt;&amp;lt;T&gt;&lt;/code&gt; is not because it involves a heap allocation that it must own and so a simple copy of the bytes would cause two objects to own the data at the same time, breaking all sorts of invariants and probably eating your laundry.
&lt;p&gt;In the &lt;a href=#rule-one&gt;first code example&lt;/a&gt;’s error, we saw the explanatory note “move occurs because &lt;code&gt;a&lt;/code&gt; has type &lt;code&gt;A&lt;/code&gt;, which does not implement the &lt;code&gt;Copy&lt;/code&gt; trait”. &lt;code&gt;A&lt;/code&gt; has move semantics; suppose we now implement the &lt;code&gt;Copy&lt;/code&gt; trait, like this:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;mark&gt;&lt;i&gt;#[derive(Clone, Copy)]&lt;/i&gt;&lt;/mark&gt;
&lt;b&gt;struct&lt;/b&gt; A {}

&lt;b&gt;fn&lt;/b&gt; main() {
    &lt;b&gt;let&lt;/b&gt; a = A {};
    &lt;b&gt;let&lt;/b&gt; b = a;
    &lt;b&gt;let&lt;/b&gt; c = a;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;figcaption&gt;
	&lt;p class=sidenote&gt;&lt;code&gt;&lt;i&gt;#[derive(X)]&lt;/i&gt;&lt;/code&gt; means “hey compiler, &lt;soft-br&gt;&lt;/soft-br&gt;I want to implement &lt;code&gt;X&lt;/code&gt; for this type, &lt;soft-br&gt;&lt;/soft-br&gt;I just want the obvious implementation, &lt;soft-br&gt;&lt;/soft-br&gt;so can you please do it for me?”
	&lt;p class=sidenote&gt;The Rust documentation &lt;a href=https://doc.rust-lang.org/std/clone/trait.Clone.html#derivable&gt;explains deriving &lt;code&gt;Clone&lt;/code&gt;&lt;/a&gt; and &lt;a href=https://doc.rust-lang.org/std/marker/trait.Copy.html#how-can-i-implement-copy&gt;&lt;code&gt;Copy&lt;/code&gt;&lt;/a&gt;.
&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;With the addition of the &lt;code&gt;Copy&lt;/code&gt; implementation for &lt;code&gt;A&lt;/code&gt;, it’s changed from having move semantics to having copy semantics, and so the code now compiles.
&lt;p&gt;There is one final matter in this exception to the rule worth mentioning: generics. If you work with a generic type, it will have move semantics unless you specify &lt;code&gt;Copy&lt;/code&gt; in its bounds. In cases where you wish to copy the value, you might wish to use &lt;a href=https://doc.rust-lang.org/std/clone/trait.Clone.html&gt;&lt;code&gt;Clone&lt;/code&gt;&lt;/a&gt; instead, as it is more general (and all types that implement &lt;code&gt;Copy&lt;/code&gt; implement &lt;code&gt;Clone&lt;/code&gt;). Don’t worry about efficiency of cloning versus copying, either; unless the writer of the type explicitly went out of their way to do so (which they should &lt;em&gt;never&lt;/em&gt; do), cloning and copying will perform identically when optimised.
&lt;p&gt;For more information on this topic, see the &lt;a href=https://doc.rust-lang.org/std/marker/trait.Copy.html&gt;&lt;code&gt;Copy&lt;/code&gt; docs&lt;/a&gt;.
&lt;h3&gt;&lt;ol&gt;&lt;li value=2&gt;Reference reborrowing&lt;/ol&gt;&lt;/h3&gt;
&lt;p&gt;A particularly notable example of a type with copy semantics is &lt;code&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;T&lt;/code&gt;; you can have as many immutable references to an object alive as you like, so long as there are no mutable references to it at the same time. &lt;code&gt;&lt;b&gt;&amp;amp;mut&lt;/b&gt; T&lt;/code&gt;, however, has move semantics, for you’re not allowed to have more than one mutable reference in scope at a time.
&lt;p&gt;So then, why does this example &lt;a href=&quot;https://play.rust-lang.org/?code=fn take_ref&lt;T&gt;(_: %26T) { }%0Afn take_mut&lt;T&gt;(_: %26mut T) { }%0Afn main() %7B%0A    let mut a %3D 6;%0A    %7B%0A        let a_ref %3D %26a;%0A        take_ref(a_ref);%0A        // Naturally this will work, for &amp;T is Copy.%0A        take_ref(a_ref);%0A    }%0A    %7B%0A        let a_mut %3D %26mut a;%0A        take_mut(a_mut);%0A        // Surely a_mut should have been consumed by the line above?%0A        take_mut(a_mut);%0A    }%0A}&quot;&gt;work&lt;/a&gt;?
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;fn&lt;/b&gt; take_ref&amp;lt;T&amp;gt;(_: &lt;b&gt;&amp;amp;&lt;/b&gt;T) { }
&lt;b&gt;fn&lt;/b&gt; take_mut&amp;lt;T&amp;gt;(_: &lt;b&gt;&amp;amp;mut&lt;/b&gt; T) { }
&lt;b&gt;fn&lt;/b&gt; main() {
    &lt;b&gt;let mut&lt;/b&gt; a = &lt;span class=n&gt;6&lt;/span&gt;;
    {
        &lt;b&gt;let&lt;/b&gt; a_ref = &lt;b&gt;&amp;amp;&lt;/b&gt;a;
        take_ref(a_ref);
        &lt;i class=c&gt;// Naturally this will work, for &amp;amp;T is Copy.&lt;/i&gt;
        take_ref(a_ref);
    }
    {
        &lt;b&gt;let&lt;/b&gt; a_mut = &lt;b&gt;&amp;amp;mut&lt;/b&gt; a;
        take_mut(a_mut);
        &lt;i class=c&gt;// Surely a_mut should have been consumed by the line above?&lt;/i&gt;
        take_mut(a_mut);
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;There is another exception in play here: reference reborrowing. Where we pass &lt;code&gt;a_mut&lt;/code&gt; to a function, it effectively becomes &lt;code&gt;&lt;b&gt;&amp;amp;mut *&lt;/b&gt;a_mut&lt;/code&gt;. This does mean that for a time two mutable references to the same thing &lt;em&gt;exist&lt;/em&gt; (one in the caller and one in the function called), but at no point are both &lt;em&gt;accessible&lt;/em&gt;, so it’s OK.
&lt;p&gt;Note that this exception only applies in situations where the parameter is of the form &lt;code&gt;&lt;b&gt;&amp;amp;mut&lt;/b&gt; T&lt;/code&gt;; if it is a generic taken by value (e.g. &lt;code&gt;&lt;b&gt;fn&lt;/b&gt;&amp;lt;T&gt;(x: T)&lt;/code&gt;) then a mutable reference you pass in will &lt;em&gt;not&lt;/em&gt; be reborrowed automatically. You can still use the &lt;code&gt;&lt;b&gt;&amp;amp;mut *&lt;/b&gt;x&lt;/code&gt; incantation to manually reborrow it, however.
&lt;h2&gt;Summary&lt;/h2&gt;
&lt;p&gt;Let’s list the main points once again:
&lt;ol&gt;
	&lt;li&gt;&lt;p&gt;Each object can be used exactly once. When you use an object it is moved to the new location and is no longer usable in the old. (&lt;code&gt;Copy&lt;/code&gt; and automatic reference reborrowing are the two exceptions that make this more palatable.)
    &lt;li&gt;&lt;p&gt;When an object passes out of scope, it is destroyed and is no longer usable.
    &lt;li&gt;&lt;p&gt;Blocks can produce a value which goes up one level of scope. (As a language feature, this is known as &lt;em&gt;expression orientation&lt;/em&gt;.)
    &lt;li&gt;&lt;p&gt;All objects have a lifetime which constrains which scopes they may be moved out of.
&lt;/ol&gt;
&lt;p&gt;These points are all that you need to understand all of Rust’s ownership model. The rules are surprisingly simple, though you can quickly get to fairly complex interactions which make things harder to reason about. Don’t worry if you haven’t understood all of this; if you are trying to learn Rust, go and do some other things for a while and come back to the article again later and you’ll probably find it makes more sense and you can understand how ownership and lifetimes work. When you finally get to that point, you’ll love Rust’s unusual ownership model.

			&lt;aside class=trailer&gt;
		&lt;hr&gt;
		&lt;p&gt;Comments? Questions? Corrections? If you want to contact me about anything in this post, email me at &lt;a href=&quot;mailto:me@chrismorgan.info&quot;&gt;me@chrismorgan.info&lt;/a&gt; or &lt;a href=https://old.reddit.com/r/rust/http://chrismorgan.info/blog/rust-ownership-the-hard-way.html&gt;discuss it on /r/rust&lt;/a&gt;.
		&lt;p&gt;Looking for more? My &lt;a href=/blog/rust-fizzbuzz/&gt;article about FizzBuzz&lt;/a&gt; is particularly relevant, dealing with these questions of ownership in a (slightly) practical context. If you’re a beginner, I suggest you also go through the &lt;a href=https://doc.rust-lang.org/&gt;official documentation&lt;/a&gt; with things like its &lt;a href=https://doc.rust-lang.org/book/README.html&gt;book&lt;/a&gt;. I have &lt;a href=/blog/tags/rust/&gt;a few more posts about Rust&lt;/a&gt; too.

	&lt;/aside&gt;
		</content>
	</entry>
	<entry xml:base="https://chrismorgan.info/blog/rust-cfg_attr/">
		<title type="html">Quick tip: the &lt;code&gt;&lt;i&gt;#[cfg_attr]&lt;/i&gt;&lt;/code&gt; attribute</title>
		<published>2015-04-22T00:00:00+00:00</published>
		<updated>2019-08-19T00:00:00+00:00</updated>
		<link href="https://chrismorgan.info/blog/rust-cfg_attr/" type="text/html"/>
		<id>http://chrismorgan.info/blog/rust-cfg_attr.html</id>
		<category scheme="https://chrismorgan.info/blog/tags/" term="rust" label="Rust" />
		<content type="html">
			&lt;p class=intro&gt;Today I want to remind people of &lt;code&gt;&lt;i&gt;#[cfg_attr]&lt;/i&gt;&lt;/code&gt;: it’s a really handy way of reducing code duplication in some situations, and not enough people know about.
			&lt;h2&gt;What is &lt;code&gt;&lt;i&gt;#[cfg_attr]&lt;/i&gt;&lt;/code&gt;?&lt;/h2&gt;
&lt;p&gt;It’s just like &lt;code&gt;&lt;i&gt;#[cfg]&lt;/i&gt;&lt;/code&gt;, but for attributes. Just as &lt;code&gt;&lt;i&gt;#[cfg(condition)]&lt;/i&gt;&lt;/code&gt; allows you to only compile the thing it decorates if the condition is true, &lt;code&gt;&lt;i&gt;#[cfg_attr(condition, attribute)]&lt;/i&gt;&lt;/code&gt; allows you to only add the attribute to the thing it decorates if the condition is true. That is, if the condition is true, it’s equivalent to &lt;code&gt;&lt;i&gt;#[attribute]&lt;/i&gt;&lt;/code&gt;, and if the condition is false, it vanishes into thin air. 
&lt;h2&gt;Real‐world examples&lt;/h2&gt;
&lt;h3&gt;Enabling nightly features in certain situations&lt;/h3&gt;
&lt;p&gt;In &lt;a href=https://crates.io/crates/anymap&gt;anymap&lt;/a&gt;, I have a &lt;code&gt;nightly&lt;/code&gt; Cargo feature which, if enabled, implements some additional features and performance optimisations (like using a more efficient hasher on the hash map) that are not yet possible on stable rustc. Those require a couple of extra gated features, but I only want the &lt;code&gt;&lt;i&gt;#![feature(core, std_misc)]&lt;/i&gt;&lt;/code&gt; crate attribute to exist if the &lt;code&gt;nightly&lt;/code&gt; Cargo feature is enabled. I can do that:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;i&gt;#![cfg_attr(feature = &lt;span class=s&gt;&quot;nightly&quot;&lt;/span&gt;, feature(core, std_misc))]&lt;/i&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;This might also be handy for things like tests:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;i&gt;#![cfg_attr(test, feature(test, anything_else_only_relevant_for_tests))]&lt;/i&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h3&gt;Special attributes for bootstrapping rustc&lt;/h3&gt;
&lt;aside class=sidenote&gt;&lt;p&gt;Since I first wrote this article,&lt;soft-br&gt;&lt;/soft-br&gt; this particular example has become obsolete;&lt;soft-br&gt;&lt;/soft-br&gt; but the principle is still sound.&lt;/p&gt;&lt;/aside&gt;
&lt;p&gt;A number of times I have noticed duplicated items, one &lt;code&gt;&lt;i&gt;#[cfg(stage0)]&lt;/i&gt;&lt;/code&gt; and one &lt;code&gt;&lt;i&gt;#[cfg(not(stage0))]&lt;/i&gt;&lt;/code&gt;, differing only in attributes; this is not necessary. I’ll take a current example:
&lt;figure&gt;
	&lt;figcaption&gt;&lt;p&gt;&lt;strong&gt;Before:&lt;/strong&gt; duplication just for one attribute’s difference.&lt;/figcaption&gt;
	&lt;pre&gt;&lt;code&gt;&lt;i&gt;&lt;b class=c&gt;/// `PhantomFn` is a deprecated marker trait that is no longer needed.&lt;/b&gt;
#[lang=&lt;span class=s&gt;&quot;phantom_fn&quot;&lt;/span&gt;]
#[stable(feature = &lt;span class=s&gt;&quot;rust1&quot;&lt;/span&gt;, since = &lt;span class=s&gt;&quot;1.0.0&quot;&lt;/span&gt;)]
#[deprecated(since = &lt;span class=s&gt;&quot;1.0.0&quot;&lt;/span&gt;, reason = &lt;span class=s&gt;&quot;No longer needed&quot;&lt;/span&gt;)]
#[cfg(stage0)]&lt;/i&gt;
&lt;b&gt;pub trait&lt;/b&gt; PhantomFn&amp;lt;A:&lt;b&gt;?Sized&lt;/b&gt;,R:&lt;b&gt;?Sized&lt;/b&gt;=()&amp;gt; {
}

&lt;i&gt;&lt;b class=c&gt;/// `PhantomFn` is a deprecated marker trait that is no longer needed.&lt;/b&gt;
#[stable(feature = &lt;span class=s&gt;&quot;rust1&quot;&lt;/span&gt;, since = &lt;span class=s&gt;&quot;1.0.0&quot;&lt;/span&gt;)]
#[deprecated(since = &lt;span class=s&gt;&quot;1.0.0&quot;&lt;/span&gt;, reason = &lt;span class=s&gt;&quot;No longer needed&quot;&lt;/span&gt;)]
#[cfg(not(stage0))]&lt;/i&gt;
&lt;b&gt;pub trait&lt;/b&gt; PhantomFn&amp;lt;A:&lt;b&gt;?Sized&lt;/b&gt;,R:&lt;b&gt;?Sized&lt;/b&gt;=()&amp;gt; {
}&lt;/code&gt;&lt;/pre&gt;
&lt;/figure&gt;
&lt;figure&gt;
	&lt;figcaption&gt;&lt;p&gt;&lt;strong&gt;After:&lt;/strong&gt; yay! no duplicating the entire thing!&lt;/figcaption&gt;
	&lt;pre&gt;&lt;code&gt;&lt;i&gt;&lt;b class=c&gt;/// `PhantomFn` is a deprecated marker trait that is no longer needed.&lt;/b&gt;
#[&lt;mark&gt;cfg_attr(stage0, &lt;/mark&gt;lang = &lt;span class=s&gt;&quot;phantom_fn&quot;&lt;/span&gt;&lt;mark&gt;)&lt;/mark&gt;]
#[stable(feature = &lt;span class=s&gt;&quot;rust1&quot;&lt;/span&gt;, since = &lt;span class=s&gt;&quot;1.0.0&quot;&lt;/span&gt;)]
#[deprecated(since = &lt;span class=s&gt;&quot;1.0.0&quot;&lt;/span&gt;, reason = &lt;span class=s&gt;&quot;No longer needed&quot;&lt;/span&gt;)]
#[cfg(stage0)]&lt;/i&gt;
&lt;b&gt;pub trait&lt;/b&gt; PhantomFn&amp;lt;A:&lt;b&gt;?Sized&lt;/b&gt;,R:&lt;b&gt;?Sized&lt;/b&gt;=()&amp;gt; {
}&lt;/code&gt;&lt;/pre&gt;
&lt;/figure&gt;
&lt;h2&gt;Bonus: doc comments are truly sugar&lt;/h2&gt;
&lt;p&gt;Dynamic doc comments is a non‐obvious area in which &lt;code&gt;&lt;i&gt;#[cfg_attr]&lt;/i&gt;&lt;/code&gt; can be used.
&lt;p&gt;First of all you must understand that these two are &lt;em&gt;precisely the same&lt;/em&gt; in all ways that matter, because the former desugars to the latter during parsing:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b class=c&gt;&lt;i&gt;/// This is the first line of the documentation.
///
/// This is another line.&lt;/i&gt;&lt;/b&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;i&gt;#[doc = &lt;span class=s&gt;&quot; This is the first line of the documentation.&quot;&lt;/span&gt;]
#[doc = &lt;span class=s&gt;&quot;&quot;&lt;/span&gt;]
#[doc = &lt;span class=s&gt;&quot; This is another line.&quot;&lt;/span&gt;]&lt;/i&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;(Multiple &lt;code&gt;&lt;i&gt;#[doc]&lt;/i&gt;&lt;/code&gt; attributes are fine; they are joined together with line breaks between to form the final doc comment.)
&lt;p&gt;This can be combined with &lt;code&gt;&lt;i&gt;#[cfg_attr]&lt;/i&gt;&lt;/code&gt; to allow conditional documentation, like adding a part to the documentation if a feature is enabled:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;i&gt;&lt;b class=c&gt;/// This trait does all sorts of cool things.
/// If the crate is built with the `foo` feature enabled,
/// it also does this other whizzy thing!
///
/// This documentation was built with the `foo` feature&lt;/b&gt;
#[cfg_attr(feature = &lt;span class=s&gt;&quot;foo&quot;&lt;/span&gt;, doc = &lt;span class=s&gt;&quot; **enabled**.&quot;&lt;/span&gt;)]
#[cfg_attr(not(feature = &lt;span class=s&gt;&quot;foo&quot;&lt;/span&gt;), doc = &lt;span class=s&gt;&quot; **disabled** (tough luck).&quot;&lt;/span&gt;)]
&lt;b class=c&gt;///
/// Now we go onto some more documentation.
///&lt;/b&gt;
#[cfg_attr(feature = &lt;span class=s&gt;&quot;bar&quot;&lt;/span&gt;, doc = &lt;span class=s&gt;&quot;&lt;b&gt;\&lt;/b&gt;
 # Barness

 You also have barness available. This is really cool stuff that lets you go
 whizzety bang pop. In real life I’d be dedicating a few paragraphs and a code
 sample or two to this. Because this isn’t real life, I’ll just ask that you
 please don’t confuse *barness* with *baroness*, because that would make me sad
 because you would be wrong.&quot;&lt;/span&gt;)]
#[cfg_attr(not(feature = &lt;span class=s&gt;&quot;bar&quot;&lt;/span&gt;), doc = &lt;span class=s&gt;&quot;&lt;b&gt;\&lt;/b&gt;
 You know, if you compiled with the `bar` feature enabled, you’d have a lot
 more fun. See [this helpful documentationy link that I will have] for details
 on how to accomplish that.&quot;&lt;/span&gt;)]&lt;/i&gt;
&lt;b&gt;trait&lt;/b&gt; Traitor { }&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;When built, the documentation will then announce whether it was built with the &lt;code&gt;foo&lt;/code&gt; feature enabled or disabled, which might be handy. And a new section will be added if the &lt;code&gt;bar&lt;/code&gt; feature is enabled, or a note on what you’re missing out on and maybe how to enable it if you don’t have it enabled. There, four versions of the documentation without the need to duplicate even a single vast swathe of code!
&lt;p&gt;Note also how when we manually write &lt;code&gt;&lt;i&gt;#[doc]&lt;/i&gt;&lt;/code&gt; attributes we put a single leading space at the start of the string; this is because &lt;code&gt;&lt;b class=c&gt;&lt;i&gt;/// Foo&lt;/i&gt;&lt;/b&gt;&lt;/code&gt; desugars to &lt;code&gt;&lt;i&gt;#[doc = &lt;span class=s&gt;&quot; Foo&quot;&lt;/span&gt;]&lt;/i&gt;&lt;/code&gt;; if all the lines start with a space, it will be trimmed from them all, but if not then such lines will have a leading space, which might mess up your Markdown formatting of things like headings marked with leading hashes.
&lt;p&gt;I will admit that dynamic doc comments isn’t going to be completely useful everywhere, for useful applications of it aren’t going to be very common and if people use only one centralised documentation source they’ll miss out on getting the special version that just suits their use case, but as we get better tooling I think it might become more appropriate. And even if it’s not so very useful (hey, it’s &lt;span class=obvious title=&quot;“Oh yeah,” I hear you say; “bonus material? That’s why it’s almost twice as long as the main part?”&quot;&gt;bonus material&lt;/span&gt;, it doesn’t need to be so very useful), it’s definitely fun.
&lt;h3&gt;Super bonus: adding macros into the mix!&lt;/h3&gt;
&lt;p&gt;Imagine that the trait bounds need to be changed if the &lt;code&gt;bar&lt;/code&gt; feature is enabled. &lt;em&gt;Argh!&lt;/em&gt; you say. &lt;em&gt;Back to the drawing board!&lt;/em&gt; Not so—​you can save all the duplication with a simple macro that, given an item and appropriate attributes, dumps them out with the documentation attributes added. Here’s a simple example:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;i&gt;macro_rules!&lt;/i&gt; define_traitor {
    (&lt;i&gt;#[&lt;span class=m&gt;$m:meta&lt;/span&gt;]&lt;/i&gt; &lt;span class=m&gt;$t:item&lt;/span&gt;) =&amp;gt; {
        &lt;i&gt;&lt;b class=c&gt;/// All the doc comment lines and&lt;/b&gt;
        #[cfg_attr(feature = &lt;span class=s&gt;&quot;bar&quot;&lt;/span&gt;, doc = &lt;span class=s&gt;&quot;cfg_attr lines and&quot;&lt;/span&gt;)]
        &lt;b class=c&gt;/// so forth.&lt;/b&gt;
        #[&lt;span class=m&gt;$m&lt;/span&gt;]&lt;/i&gt; &lt;span class=m&gt;$t&lt;/span&gt;
    }
}

&lt;i&gt;define_traitor!&lt;/i&gt; {
    &lt;i&gt;#[cfg(not(feature = &lt;span class=s&gt;&quot;bar&quot;&lt;/span&gt;))]&lt;/i&gt;
    &lt;b&gt;trait&lt;/b&gt; Traitor { }
}

&lt;i&gt;define_traitor!&lt;/i&gt; {
    &lt;i&gt;#[cfg(feature = &lt;span class=s&gt;&quot;bar&quot;&lt;/span&gt;)]&lt;/i&gt;
    &lt;b&gt;trait&lt;/b&gt; Traitor: BarOfChocolate { }
    &lt;span class=c&gt;// Yeah, a traitor can depend on a bar of chocolate, why not?&lt;/span&gt;
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;&lt;i class=obvious title=&quot;Or “Viola!” if you prefer string instruments. Up you, really.&quot;&gt;Voilà!&lt;/i&gt; Whichever version of the &lt;code&gt;Traitor&lt;/code&gt; trait we get, it has the right documentation on it.

			&lt;aside class=trailer&gt;
		&lt;hr&gt;
		&lt;p&gt;Comments? Questions? Corrections? If you want to contact me about anything in this post, email me at &lt;a href=&quot;mailto:me@chrismorgan.info&quot;&gt;me@chrismorgan.info&lt;/a&gt;.
	&lt;/aside&gt;
		</content>
	</entry>
	<entry xml:base="https://chrismorgan.info/blog/rust-fizzbuzz/">
		<title type="html">&lt;strong&gt;Why your first FizzBuzz implementation may not work:&lt;/strong&gt; an exploration into some initially surprising but great parts of Rust (though you still may not like them)</title>
		<published>2014-10-03T00:00:00+00:00</published>
		<updated>2022-01-29T00:00:00+00:00</updated>
		<link href="https://chrismorgan.info/blog/rust-fizzbuzz/" type="text/html"/>
		<id>http://chrismorgan.info/blog/rust-fizzbuzz.html</id>
		<category scheme="https://chrismorgan.info/blog/tags/" term="rust" label="Rust" />
		<content type="html">
			&lt;p class=intro&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Fizz_buzz#Other_uses&quot;&gt;FizzBuzz&lt;/a&gt; is intended as a simple task, but in Rust there are a few pitfalls for the novice to be aware of. These aren’t problems with Rust but rather differences from what people are commonly familiar with, restrictions that may seem arduous at first but ultimately give you more power, at a small cost.
			&lt;h2&gt;A simple functional implementation&lt;/h2&gt;
&lt;p&gt;OK, I said in the title that your &lt;em&gt;first&lt;/em&gt; FizzBuzz implementation might not work—​then again, it might. You might write it like this which follows, for example, a way that works fine.
&lt;figure id=figure-1&gt;
	&lt;figcaption class=with-captioned-subfigure&gt;
		&lt;p&gt;&lt;strong&gt;Figure 1:&lt;/strong&gt; a simple FizzBuzz implementation with separate print statements: easy and functional.&lt;/p&gt;

		&lt;p&gt;(For brevity of the code examples, &lt;soft-br&gt;&lt;/soft-br&gt;assume that the Rust code is always &lt;soft-br&gt;&lt;/soft-br&gt;wrapped in &lt;code&gt;&lt;b&gt;fn&lt;/b&gt; main() { … }&lt;/code&gt;.)&lt;/p&gt;
	&lt;/figcaption&gt;
	&lt;div class=line-between&gt;
		&lt;figure&gt;
			&lt;figcaption&gt;Rust&lt;/figcaption&gt;
			&lt;pre&gt;&lt;code&gt;&lt;b&gt;for&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; &lt;span class=n&gt;1&lt;/span&gt;..&lt;span class=n&gt;101&lt;/span&gt; {
    &lt;b&gt;if&lt;/b&gt; i % &lt;span class=n&gt;15&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;FizzBuzz&quot;&lt;/span&gt;);
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;5&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;Buzz&quot;&lt;/span&gt;);
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;3&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;Fizz&quot;&lt;/span&gt;);
    } &lt;b&gt;else&lt;/b&gt; {
        &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;&lt;b&gt;{}&lt;/b&gt;&quot;&lt;/span&gt;, i);
    }
}
&lt;/code&gt;&lt;/pre&gt;
		&lt;/figure&gt;

		&lt;figure&gt;
			&lt;figcaption&gt;Python&lt;/figcaption&gt;
			&lt;pre&gt;&lt;code&gt;&lt;b&gt;for&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; range(&lt;span class=n&gt;1&lt;/span&gt;, &lt;span class=n&gt;101&lt;/span&gt;):
    &lt;b&gt;if&lt;/b&gt; i % &lt;span class=n&gt;15&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt;:
        print(&lt;span class=s&gt;&apos;FizzBuzz&apos;&lt;/span&gt;)
    &lt;b&gt;elif&lt;/b&gt; i % &lt;span class=n&gt;5&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt;:
        print(&lt;span class=s&gt;&apos;Buzz&apos;&lt;/span&gt;)
    &lt;b&gt;elif&lt;/b&gt; i % &lt;span class=n&gt;3&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt;:
        print(&lt;span class=s&gt;&apos;Fizz&apos;&lt;/span&gt;)
    &lt;b&gt;else&lt;/b&gt;:
        print(i)
&lt;/code&gt;&lt;/pre&gt;
		&lt;/figure&gt;
	&lt;/div&gt;
&lt;/figure&gt;
&lt;p&gt;These programs will both produce the desired output and they’re evidently very similar visually. The main thing to note about the Rust version is that &lt;code&gt;&lt;i&gt;println!&lt;/i&gt;()&lt;/code&gt; needs as its first argument a string literal, a formatting string; in Python it’d be equivalent to &lt;code&gt;print(&lt;span class=s&gt;&apos;&lt;b&gt;{}&lt;/b&gt;&apos;&lt;/span&gt;.format(i))&lt;/code&gt;.
&lt;p&gt;But how about if we decided that we wanted only one print call in the code base? Here’s how it might go:
&lt;figure id=figure-2&gt;
	&lt;figcaption class=with-captioned-subfigure&gt;
		&lt;p&gt;&lt;strong&gt;Figure 2:&lt;/strong&gt; storing the result in a variable, &lt;soft-br&gt;&lt;/soft-br&gt;so as to use only one print statement.
		&lt;p&gt;&lt;code&gt;&lt;b&gt;if&lt;/b&gt;&lt;/code&gt; block as an expression; the whole &lt;code&gt;result&lt;/code&gt; variable assignment is actually unnecessary, we could just put the &lt;code&gt;&lt;b&gt;if&lt;/b&gt;&lt;/code&gt; block straight where it’s subsequently used. Ruby programmers may recognise this as &lt;em&gt;expression orientation&lt;/em&gt;. As a Python programmer when I came to Rust, I thought it just a gimmick to let you omit &lt;code&gt;&lt;b&gt;return&lt;/b&gt;&lt;/code&gt;; but I rapidly discovered that it’s a marvellous paradigm. Rust totally ruined Python for me.
	&lt;/figcaption&gt;
	&lt;div class=line-between&gt;
		&lt;figure&gt;
			&lt;figcaption&gt;Rust (won’t compile)&lt;/figcaption&gt;
			&lt;pre&gt;&lt;code&gt;&lt;b&gt;for&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; &lt;span class=n&gt;1&lt;/span&gt;..&lt;span class=n&gt;101&lt;/span&gt; {
    &lt;b&gt;let&lt;/b&gt; result = &lt;b&gt;if&lt;/b&gt; i % &lt;span class=n&gt;15&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;FizzBuzz&quot;&lt;/span&gt;
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;5&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;Buzz&quot;&lt;/span&gt;
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;3&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;Fizz&quot;&lt;/span&gt;
    } &lt;b&gt;else&lt;/b&gt; {
        i
    };
    &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;&lt;b&gt;{}&lt;/b&gt;&quot;&lt;/span&gt;, result);
}
&lt;/code&gt;&lt;/pre&gt;
		&lt;/figure&gt;

		&lt;figure&gt;
			&lt;figcaption&gt;Python&lt;/figcaption&gt;
			&lt;pre&gt;&lt;code&gt;&lt;b&gt;for&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; range(&lt;span class=n&gt;1&lt;/span&gt;, &lt;span class=n&gt;101&lt;/span&gt;):
    &lt;b&gt;if&lt;/b&gt; i % &lt;span class=n&gt;15&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt;:
        result = &lt;span class=s&gt;&apos;FizzBuzz&apos;&lt;/span&gt;
    &lt;b&gt;elif&lt;/b&gt; i % &lt;span class=n&gt;5&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt;:
        result = &lt;span class=s&gt;&apos;Buzz&apos;&lt;/span&gt;
    &lt;b&gt;elif&lt;/b&gt; i % &lt;span class=n&gt;3&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt;:
        result = &lt;span class=s&gt;&apos;Fizz&apos;&lt;/span&gt;
    &lt;b&gt;else&lt;/b&gt;:
        result = i

    print(result)
&lt;/code&gt;&lt;/pre&gt;
		&lt;/figure&gt;
	&lt;/div&gt;
&lt;/figure&gt;
&lt;p&gt;This Rust code may seem all very well, but it’s actually not, owing to its strict typing rules. For what is the type of the variable &lt;code&gt;result&lt;/code&gt;? The first three branches of the if‐expression produce strings and the fourth an integer:
&lt;figure class=compiler-output id=figure-2a&gt;
	&lt;figcaption&gt;
		&lt;p&gt;&lt;strong&gt;Figure 2a:&lt;/strong&gt; compiler output for &lt;a href=#figure-2&gt;Figure 2&lt;/a&gt;.

		&lt;p&gt;&lt;code&gt;{integer}&lt;/code&gt; identifies a partially‐resolved type and is used for integer literals, when the compiler hasn’t yet determined what actual type it will be. An integer literal can be of type &lt;code&gt;&lt;b&gt;u8&lt;/b&gt;&lt;/code&gt;, &lt;code&gt;&lt;b&gt;i8&lt;/b&gt;&lt;/code&gt;, &lt;code&gt;&lt;b&gt;u16&lt;/b&gt;&lt;/code&gt;, &lt;code&gt;&lt;b&gt;i16&lt;/b&gt;&lt;/code&gt;, &lt;code&gt;&lt;b&gt;u32&lt;/b&gt;&lt;/code&gt;, &lt;code&gt;&lt;b&gt;i32&lt;/b&gt;&lt;/code&gt;, &lt;code&gt;&lt;b&gt;u64&lt;/b&gt;&lt;/code&gt;, &lt;code&gt;&lt;b&gt;i64&lt;/b&gt;&lt;/code&gt;, &lt;code&gt;&lt;b&gt;u128&lt;/b&gt;&lt;/code&gt;, &lt;code&gt;&lt;b&gt;i128&lt;/b&gt;&lt;/code&gt;, &lt;code&gt;&lt;b&gt;usize&lt;/b&gt;&lt;/code&gt; or &lt;code&gt;&lt;b&gt;isize&lt;/b&gt;&lt;/code&gt;. If the compiler doesn’t get any hints as to what it should be, it’ll end up choosing &lt;code&gt;&lt;b&gt;i32&lt;/b&gt;&lt;/code&gt;.
	&lt;/figcaption&gt;
	&lt;pre&gt;&lt;samp&gt;&lt;b&gt;&lt;span class=ansi-red&gt;error[&lt;a href=https://doc.rust-lang.org/error-index.html#E0308&gt;&lt;span class=ansi-red&gt;E0308&lt;/span&gt;&lt;/a&gt;]&lt;/span&gt;: if and else have incompatible types&lt;/b&gt;
&lt;b class=ansi-blue&gt;  --&amp;gt;&lt;/b&gt; &amp;lt;anon&amp;gt;:10:9
&lt;b class=ansi-blue&gt;   |&lt;/b&gt;
&lt;b class=ansi-blue&gt;7  |&lt;/b&gt;       } else if i % 3 == 0 {
&lt;b class=ansi-blue&gt;   |  ____________-&lt;/b&gt;
&lt;b class=ansi-blue&gt;8  | |&lt;/b&gt;         &quot;Fizz&quot;
&lt;b class=ansi-blue&gt;   | |         ------ expected because of this&lt;/b&gt;
&lt;b class=ansi-blue&gt;9  | |&lt;/b&gt;     } else {
&lt;b class=ansi-blue&gt;10 | |&lt;/b&gt;         i
&lt;b class=ansi-blue&gt;   | |&lt;/b&gt;         &lt;b class=ansi-red&gt;^ expected `&amp;amp;str`, found integer&lt;/b&gt;
&lt;b class=ansi-blue&gt;11 | |&lt;/b&gt;     };
&lt;b class=ansi-blue&gt;   | |_____- `if` and `else` have incompatible types&lt;/b&gt;

&lt;b&gt;&lt;span class=ansi-red&gt;error&lt;/span&gt;: aborting due to previous error&lt;/b&gt;&lt;/samp&gt;&lt;/pre&gt;
&lt;/figure&gt;
&lt;p&gt;This clearly won’t do. How about we turn it into a string first?
&lt;figure id=figure-3&gt;
	&lt;figcaption&gt;
		&lt;p&gt;&lt;strong&gt;Figure 3:&lt;/strong&gt; adding &lt;code&gt;.to_string()&lt;/code&gt; &lt;soft-br&gt;&lt;/soft-br&gt;to the code from &lt;a href=#figure-2&gt;Figure 2&lt;/a&gt;.
	&lt;/figcaption&gt;
	&lt;pre&gt;&lt;code&gt;&lt;b&gt;for&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; &lt;span class=n&gt;1&lt;/span&gt;..&lt;span class=n&gt;101&lt;/span&gt; {
    &lt;b&gt;let&lt;/b&gt; result = &lt;b&gt;if&lt;/b&gt; i % &lt;span class=n&gt;15&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;FizzBuzz&quot;&lt;/span&gt;
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;5&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;Buzz&quot;&lt;/span&gt;
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;3&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;Fizz&quot;&lt;/span&gt;
    } &lt;b&gt;else&lt;/b&gt; {
        i&lt;mark&gt;.to_string()&lt;/mark&gt;
    };
    &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;&lt;b&gt;{}&lt;/b&gt;&quot;&lt;/span&gt;, result);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;/figure&gt;
&lt;p&gt;This is where we stray from the familiar parts of computer science that most people are familiar with to a part that far fewer people will relate to. Because this &lt;em&gt;doesn’t work&lt;/em&gt;.
&lt;figure class=compiler-output id=figure-3a&gt;
	&lt;figcaption&gt;
		&lt;p&gt;&lt;strong&gt;Figure 3a:&lt;/strong&gt; compiler output for &lt;a href=#figure-3&gt;Figure 3&lt;/a&gt;.
		&lt;p&gt;Note that from Rust 1.58 this produces a spurious second error related to integer type inference; I’ve &lt;a href=https://github.com/rust-lang/rust/issues/93450&gt;reported this&lt;/a&gt;, hopefully it’ll be resolved soon.
	&lt;/figcaption&gt;
	&lt;pre&gt;&lt;samp&gt;&lt;b&gt;&lt;span class=ansi-red&gt;error[&lt;a href=https://doc.rust-lang.org/error-index.html#E0308&gt;&lt;span class=ansi-red&gt;E0308&lt;/span&gt;&lt;/a&gt;]&lt;/span&gt;: if and else have incompatible types&lt;/b&gt;
&lt;b class=ansi-blue&gt;  --&amp;gt;&lt;/b&gt; &amp;lt;anon&amp;gt;:10:9
&lt;b class=ansi-blue&gt;   |&lt;/b&gt;
&lt;b class=ansi-blue&gt;7  |&lt;/b&gt;       } else if i % 3 == 0 {
&lt;b class=ansi-blue&gt;   |  ____________-&lt;/b&gt;
&lt;b class=ansi-blue&gt;8  | |&lt;/b&gt;         &quot;Fizz&quot;
&lt;b class=ansi-blue&gt;   | |         ------ expected because of this&lt;/b&gt;
&lt;b class=ansi-blue&gt;9  | |&lt;/b&gt;     } else {
&lt;b class=ansi-blue&gt;10 | |&lt;/b&gt;         i.to_string()
&lt;b class=ansi-blue&gt;   | |&lt;/b&gt;         &lt;b class=ansi-red&gt;^^^^^^^^^^^^^ expected `&amp;amp;str`, found struct `String`&lt;/b&gt;
&lt;b class=ansi-blue&gt;11 | |&lt;/b&gt;     };
&lt;b class=ansi-blue&gt;   | |_____- `if` and `else` have incompatible types&lt;/b&gt;

&lt;b&gt;&lt;span class=ansi-red&gt;error&lt;/span&gt;: aborting due to previous error&lt;/b&gt;&lt;/samp&gt;&lt;/pre&gt;
&lt;/figure&gt;
&lt;p&gt;“What?” I hear you saying; “aren’t they both strings? What’s the deal with this &amp;amp;str (how do I even pronounce it? [I can’t even decide whether to spell its indefinite article “a” or “an”. Sometimes I say “an ampersand str”, sometimes “a str”, sometimes “a str reference” or “a str slice” (inverted order). &lt;code&gt;&lt;b&gt;&amp;amp;&lt;i class=s&gt;&apos;static&lt;/i&gt; str&lt;/b&gt;&lt;/code&gt; I call “a static str”. &lt;code&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; &lt;b&gt;str&lt;/b&gt;&lt;/code&gt; I mostly say something like “a str slice, lifetime &lt;em&gt;a&lt;/em&gt;”.]) and String?” Now indeed I need to be more specific than I was in the previous analysis of the types of the branches: the first three branches didn’t just produce “strings”, they each produced a &lt;code&gt;&lt;b&gt;&amp;amp;str&lt;/b&gt;&lt;/code&gt;; the fourth branch produced a generic integer, which might be of a number of types (though in the absence of any further information it would become a &lt;code&gt;&lt;b&gt;i32&lt;/b&gt;&lt;/code&gt;, the default type of integer). Languages like Python, Ruby and JavaScript unify their integer types (actually, JavaScript unifies its number types altogether), while languages like C♯ and Java and Go have a variety of integral types of different sizes, so there being multiple integer types is familiar to many. But even C♯, Java and Go each have just one type of string. &lt;!-- C++? Well, it’s kind of a mess. --&gt;
&lt;p&gt;Rust doesn’t. It has two.
&lt;h2&gt;Two types of strings? What &lt;!-- madness, folly, choose your own word --&gt; is this?&lt;/h2&gt;
&lt;p&gt;We could look at a simple explanation and continue on our way, but we’ve come so far down this pathway that we might as well go the rest of the way—​understanding &lt;em&gt;specifically&lt;/em&gt; what’s going on is definitely worthwhile. Why can C♯ and Java and Go get away with one String type and Rust can’t? To answer this, we have to step down to the level of memory management.
&lt;p&gt;C♯, Java and Go are all &lt;em&gt;managed languages&lt;/em&gt; (also known as &lt;em&gt;garbage collected languages&lt;/em&gt;). That is, they have a runtime which takes care of the allocation and freeing of memory at the appropriate times; when nothing is using the string any more, it can be freed. They can thus return references to a string and not need to worry about liveness issues: parts of a string that are in use will not be freed.
&lt;p&gt;There is a trade‐off here for them; as a general rule, such languages have immutable strings—​if you concatenate two strings, it involves a completely new allocation. (This means that a solution that modifies a string by adding “Fizz” if it’s divisible by three and then “Buzz” if it’s divisible by five and then the number if the string is still empty may well involve two allocations for multiples of fifteen, though something called &lt;em&gt;string interning&lt;/em&gt; which is commonly employed may reduce or fix that, depending on how it’s done and how clever any optimiser is.) This is, I presume, because the alternatives are worse: copying for any slicing will lead to a very significant increase in memory usage for most programs; and allowing mutation of one string to potentially affect others derived from it is terrible for correctness, and it could lead to nasty data race conditions in what is for practical purposes a primitive type, and it could also, for anything using UTF‐16 or UTF‐8&lt;!-- or more generally, any variable‐width encodings; UCS‐2 would be fine, but not UTF‐16. Oh, by the way—​I hate surrogate pairs --&gt;, lead to illegal code points in a subslice (substring); sure, most of these problems arise in other places, but having it in their string types would be much worse. (I said that they only have one string type, but that also is typically not quite true—​there are enough cases that need more efficient mutable strings that they tend to have such a type. For example, Java and .NET have things called &lt;code&gt;StringBuilder&lt;/code&gt;.)
&lt;p&gt;Rust’s model is somewhat different, not being a garbage collected language, being centred around its language-wide model of &lt;em&gt;ownership&lt;/em&gt;, where each object is owned in one place at a time, though other places may safely borrow references to it.
&lt;p&gt;&lt;code&gt;String&lt;/code&gt; is an &lt;em&gt;owned&lt;/em&gt; type. That is, it has exclusive ownership of the contents of the string; and when it passes out of scope, the memory for the contents of the string will be freed immediately. For this reason, any substring can’t be of the type &lt;code&gt;String&lt;/code&gt;, for there will be no connection between the two, and so when one passed out of scope, the other would become invalid, leading to a loss of memory safety. And so instead it is that slices (substrings) use a type which is a &lt;em&gt;reference&lt;/em&gt; to the contents that something else owns—​&lt;code&gt;&lt;b&gt;&amp;amp;str&lt;/b&gt;&lt;/code&gt;. Rust, through its concept of &lt;em&gt;lifetimes&lt;/em&gt;, is able to guarantee that no slice outlives the actual &lt;code&gt;String&lt;/code&gt;, and so memory safety is ensured.
&lt;p&gt;Lifetimes have syntax, &lt;code&gt;&lt;i class=s&gt;&apos;like_this&lt;/i&gt;&lt;/code&gt;, with one special lifetime &lt;code&gt;&lt;b&gt;&lt;i class=s&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&lt;/code&gt; that indicates the life of the program. But when there’s only one possible value or an obvious way things should be hooked up, you can normally skip writing the lifetime; this is called &lt;em&gt;lifetime elision&lt;/em&gt;. We’ll encounter lifetimes a bit later in this article, but so far they’ve all been elided. Just to prepare you: a string slice of lifetime &lt;em&gt;a&lt;/em&gt; is spelled &lt;code&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a &lt;/i&gt;&lt;b&gt;str&lt;/b&gt;&lt;/code&gt;, and string literals (being stored in the binary) are &lt;code&gt;&lt;b&gt;&amp;amp;&lt;i class=s&gt;&apos;static &lt;/i&gt;str&lt;/b&gt;&lt;/code&gt;.
&lt;p&gt;If you’re interested in learning more about lifetimes at this point, &lt;a href=https://doc.rust-lang.org/book/lifetimes.html&gt;the Rust Book has a chapter on them&lt;/a&gt;.
&lt;aside&gt;
	&lt;p&gt;If you know a &lt;em&gt;little&lt;/em&gt; more about Rust types, you may wonder why &lt;code&gt;String&lt;/code&gt; is used instead of &lt;code&gt;&lt;b&gt;Box&lt;/b&gt;&amp;lt;&lt;b&gt;str&lt;/b&gt;&amp;gt;&lt;/code&gt;. The answer lies in the difference between the two types: &lt;code&gt;&lt;b&gt;Box&lt;/b&gt;&amp;lt;&lt;b&gt;str&lt;/b&gt;&amp;gt;&lt;/code&gt; is a fixed‐size allocation, so you’d need to reallocate every time you push to the string, but &lt;code&gt;String&lt;/code&gt; overallocates for efficiency in the usual case, storing a &lt;em&gt;capacity&lt;/em&gt; member also to track that. So &lt;code&gt;String&lt;/code&gt; is normally the more suitable of the two.
	&lt;p&gt;Things really aren’t so very different from how they are in most other languages; it really is just that the lack of mandatory garbage collection stops some uses of &lt;code&gt;&lt;b&gt;&amp;amp;str&lt;/b&gt;&lt;/code&gt;, making it so that you have to reach for the growable string buffer more often than you would have to in other languages, because they allow you to be sloppy with their main string type.
&lt;/aside&gt;
&lt;h2&gt;Back to the fizzing and buzzing&lt;/h2&gt;
&lt;p&gt;So then, the problem is that one of them is an owned string while the other three are string slices (references to statically defined strings). How shall we resolve it? How about we try making them all string slices (that is, of type &lt;code&gt;&lt;b&gt;&amp;amp;str&lt;/b&gt;&lt;/code&gt;):
&lt;figure id=figure-4&gt;
	&lt;pre&gt;&lt;code&gt;&lt;b&gt;for&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; &lt;span class=n&gt;1&lt;/span&gt;..&lt;span class=n&gt;101&lt;/span&gt; {
    &lt;b&gt;let&lt;/b&gt; result = &lt;b&gt;if&lt;/b&gt; i % &lt;span class=n&gt;15&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;FizzBuzz&quot;&lt;/span&gt;
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;5&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;Buzz&quot;&lt;/span&gt;
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;3&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;Fizz&quot;&lt;/span&gt;
    } &lt;b&gt;else&lt;/b&gt; {
        &lt;mark&gt;&lt;b&gt;&amp;amp;*&lt;/b&gt;&lt;/mark&gt;i.to_string()
    };
    &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;&lt;b&gt;{}&lt;/b&gt;&quot;&lt;/span&gt;, result);
}
&lt;/code&gt;&lt;/pre&gt;
	&lt;figcaption&gt;
		&lt;p&gt;&lt;strong&gt;Figure 4:&lt;/strong&gt; adding &lt;code&gt;&lt;b&gt;&amp;amp;*&lt;/b&gt;&lt;/code&gt; to the code from &lt;a href=#figure-3&gt;Figure 3&lt;/a&gt; &lt;soft-br&gt;&lt;/soft-br&gt;to convert the &lt;code&gt;String&lt;/code&gt; to &lt;code&gt;&lt;b&gt;&amp;amp;str&lt;/b&gt;&lt;/code&gt;.

		&lt;p&gt;&lt;code&gt;String&lt;/code&gt; dereferences to &lt;code&gt;&lt;b&gt;str&lt;/b&gt;&lt;/code&gt;—​&lt;i&gt;viz.&lt;/i&gt;, it implements &lt;code&gt;Deref&amp;lt;Target = &lt;b&gt;str&lt;/b&gt;&amp;gt;&lt;/code&gt;—​so &lt;code&gt;&lt;b&gt;&amp;amp;*&lt;/b&gt;string&lt;/code&gt; produces a string slice, type &lt;code&gt;&lt;b&gt;&amp;amp;str&lt;/b&gt;&lt;/code&gt;, pointing to the contents of the &lt;code&gt;String&lt;/code&gt;.
	&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;That seems like a good idea, right? Sorry, that won’t do:
&lt;figure class=compiler-output id=figure-4a&gt;
	&lt;figcaption&gt;
		&lt;p&gt;&lt;strong&gt;Figure 4a:&lt;/strong&gt; compiler output for &lt;a href=#figure-4&gt;Figure 4&lt;/a&gt;.
	&lt;/figcaption&gt;
	&lt;pre&gt;&lt;samp&gt;&lt;b&gt;&lt;span class=ansi-red&gt;error[&lt;a href=https://doc.rust-lang.org/error-index.html#E0716&gt;&lt;span class=ansi-red&gt;E0716&lt;/span&gt;&lt;/a&gt;]&lt;/span&gt;: temporary value dropped while borrowed&lt;/b&gt;
&lt;b class=ansi-blue&gt;  --&amp;gt;&lt;/b&gt; &amp;lt;anon&amp;gt;:10:11
&lt;b class=ansi-blue&gt;   |&lt;/b&gt;
&lt;b class=ansi-blue&gt;7  |&lt;/b&gt;       } else if i % 3 == 0 {
&lt;b class=ansi-blue&gt;   |  ____________-&lt;/b&gt;
&lt;b class=ansi-blue&gt;8  | |&lt;/b&gt;         &quot;Fizz&quot;
&lt;b class=ansi-blue&gt;9  | |&lt;/b&gt;     } else {
&lt;b class=ansi-blue&gt;10 | |&lt;/b&gt;         &amp;amp;*i.to_string()
&lt;b class=ansi-blue&gt;   | |&lt;/b&gt;           &lt;b class=ansi-red&gt;^^^^^^^^^^^^^ creates a temporary which is freed while still in use&lt;/b&gt;
&lt;b class=ansi-blue&gt;11 | |&lt;/b&gt;     };
&lt;b class=ansi-blue&gt;   | |     -&lt;/b&gt;
&lt;b class=ansi-blue&gt;   | |     |&lt;/b&gt;
&lt;b class=ansi-blue&gt;   | |_____temporary value is freed at the end of this statement&lt;/b&gt;
&lt;b class=ansi-blue&gt;   |       borrow later used here&lt;/b&gt;
&lt;b class=ansi-blue&gt;   |&lt;/b&gt;
&lt;b&gt;   &lt;span class=ansi-blue&gt;=&lt;/span&gt; note&lt;/b&gt;: consider using a `let` binding to create a longer lived value

&lt;b&gt;&lt;span class=ansi-red&gt;error&lt;/span&gt;: aborting due to previous error&lt;/b&gt;&lt;/samp&gt;&lt;/pre&gt;
&lt;/figure&gt;
&lt;p&gt;Here we’re running into a lifetime issue; the &lt;code&gt;String&lt;/code&gt; created by &lt;code&gt;i.to_string()&lt;/code&gt; is not being stored anywhere, and so it is freed at the end of the &lt;code&gt;&lt;b&gt;else&lt;/b&gt;&lt;/code&gt; block. Thus the reference to it can’t escape that block, like we were trying to make happen. This is a memory safety bug that the Rust compiler caught; in some languages it would wind up as a &lt;em&gt;dangling pointer&lt;/em&gt;, which is a Very Bad Thing.
&lt;p&gt;Now in this case, the compiler gave us a suggestion: “consider using a `let` binding to create a longer lived value”. Not all of the compiler’s suggestions will be workable, but I think this one always is if it makes it. We can indeed lift the &lt;code&gt;String&lt;/code&gt; variable to outside the &lt;code&gt;&lt;b&gt;else&lt;/b&gt;&lt;/code&gt; block; the compiler was only caring that the object being referenced needed to be valid for the body of the &lt;code&gt;&lt;b&gt;for&lt;/b&gt;&lt;/code&gt; loop. Here’s how that looks:
&lt;figure id=figure-5&gt;
	&lt;pre&gt;&lt;code&gt;&lt;b&gt;for&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; &lt;span class=n&gt;1&lt;/span&gt;..&lt;span class=n&gt;101&lt;/span&gt; {
&lt;mark&gt;    &lt;b&gt;let&lt;/b&gt; x;&lt;/mark&gt;
    &lt;b&gt;let&lt;/b&gt; result = &lt;b&gt;if&lt;/b&gt; i % &lt;span class=n&gt;15&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;FizzBuzz&quot;&lt;/span&gt;
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;5&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;Buzz&quot;&lt;/span&gt;
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;3&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;Fizz&quot;&lt;/span&gt;
    } &lt;b&gt;else&lt;/b&gt; {
        &lt;mark&gt;x = &lt;/mark&gt;i.to_string()&lt;mark&gt;;
        &lt;/mark&gt;&lt;b&gt;&amp;amp;*&lt;/b&gt;&lt;mark&gt;x&lt;/mark&gt;
    };
    &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;&lt;b&gt;{}&lt;/b&gt;&quot;&lt;/span&gt;, result);
}
&lt;/code&gt;&lt;/pre&gt;
	&lt;figcaption&gt;
		&lt;!-- TODO: actually make soft-br support two in one paragraph. --&gt;
		&lt;p&gt;&lt;strong&gt;Figure 5:&lt;/strong&gt; taking a reference as in &lt;soft-br&gt;&lt;/soft-br&gt;&lt;a href=#figure-4&gt;Figure 4&lt;/a&gt;, but storing the owned &lt;soft-br&gt;&lt;/soft-br&gt;string in the outer scope: this works.
		&lt;p&gt;This way, the &lt;code&gt;String&lt;/code&gt; lives until the end of the for‐loop, which is longer than &lt;code&gt;result&lt;/code&gt; needs to be valid for, and so &lt;code&gt;result&lt;/code&gt; is allowed to refer to it.
	&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;h2&gt;How about we make it a &lt;code&gt;String&lt;/code&gt;?&lt;/h2&gt;
&lt;p&gt;Another direction that we could go is to make all of the branches return owned strings:
&lt;figure id=figure-6&gt;
	&lt;pre&gt;&lt;code&gt;&lt;b&gt;for&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; &lt;span class=n&gt;1&lt;/span&gt;..&lt;span class=n&gt;101&lt;/span&gt; {
    &lt;b&gt;let&lt;/b&gt; result = &lt;b&gt;if&lt;/b&gt; i % &lt;span class=n&gt;15&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;FizzBuzz&quot;&lt;/span&gt;&lt;mark&gt;.to_string()&lt;/mark&gt;
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;5&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;Buzz&quot;&lt;/span&gt;&lt;mark&gt;.to_string()&lt;/mark&gt;
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;3&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;Fizz&quot;&lt;/span&gt;&lt;mark&gt;.to_string()&lt;/mark&gt;
    } &lt;b&gt;else&lt;/b&gt; {
        i&lt;mark&gt;.to_string()&lt;/mark&gt;
    };
    &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;&lt;b&gt;{}&lt;/b&gt;&quot;&lt;/span&gt;, result);
}
&lt;/code&gt;&lt;/pre&gt;
	&lt;figcaption&gt;
		&lt;p&gt;&lt;strong&gt;Figure 6:&lt;/strong&gt; &lt;code&gt;String&lt;/code&gt; all the way:&lt;soft-br&gt;&lt;/soft-br&gt; this works, at a runtime cost.&lt;/p&gt;
	&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;This will work fine, but it has meant that a new chunk of memory is allocated for &lt;em&gt;all&lt;/em&gt; values of &lt;code&gt;i&lt;/code&gt;, rather than just for the ones which aren’t factors of three or five.
&lt;h2&gt;Making it a function&lt;/h2&gt;
&lt;p&gt;We’ve gone as far as we can in this direction without things becoming absurd; how about if we alter the parameters of the problem so that we’re not &lt;em&gt;printing&lt;/em&gt; the result, but rather returning it from a function?
&lt;p&gt;Here’s what we might start with:
&lt;!-- Look at how restrained I was with the Python version! No annotations (`def fizz_buzz(i: int) -&gt; str:`) at all! --&gt;
&lt;figure id=figure-7&gt;
	&lt;figcaption class=with-captioned-subfigure&gt;
		&lt;p&gt;&lt;strong&gt;Figure 7:&lt;/strong&gt; the &lt;code&gt;fizz_buzz&lt;/code&gt; function,&lt;soft-br&gt;&lt;/soft-br&gt; with &lt;code&gt;String&lt;/code&gt;s.&lt;/p&gt;
	&lt;/figcaption&gt;
	&lt;div class=line-between&gt;
		&lt;figure&gt;
			&lt;figcaption&gt;Rust&lt;/figcaption&gt;
			&lt;pre&gt;&lt;code&gt;&lt;b&gt;fn&lt;/b&gt; fizz_buzz(i: &lt;b&gt;i32&lt;/b&gt;) -&amp;gt; String {
    &lt;b&gt;if&lt;/b&gt; i % &lt;span class=n&gt;15&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;FizzBuzz&quot;&lt;/span&gt;.to_string()
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;5&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;Buzz&quot;&lt;/span&gt;.to_string()
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;3&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;Fizz&quot;&lt;/span&gt;.to_string()
    } &lt;b&gt;else&lt;/b&gt; {
        i.to_string()
    }
}

&lt;b&gt;for&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; &lt;span class=n&gt;1&lt;/span&gt;..&lt;span class=n&gt;101&lt;/span&gt; {
    &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;&lt;b&gt;{}&lt;/b&gt;&quot;&lt;/span&gt;, fizz_buzz(i));
}
&lt;/code&gt;&lt;/pre&gt;
		&lt;/figure&gt;

		&lt;figure&gt;
			&lt;figcaption&gt;Python&lt;/figcaption&gt;
&lt;pre&gt;&lt;code&gt;&lt;b&gt;def&lt;/b&gt; fizz_buzz(i):
    &lt;b&gt;if&lt;/b&gt; i % &lt;span class=n&gt;15&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt;:
        &lt;b&gt;return&lt;/b&gt; &lt;span class=s&gt;&apos;FizzBuzz&apos;&lt;/span&gt;
    &lt;b&gt;elif&lt;/b&gt; i % &lt;span class=n&gt;5&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt;:
        &lt;b&gt;return&lt;/b&gt; &lt;span class=s&gt;&apos;Buzz&apos;&lt;/span&gt;
    &lt;b&gt;elif&lt;/b&gt; i % &lt;span class=n&gt;3&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt;:
        &lt;b&gt;return&lt;/b&gt; &lt;span class=s&gt;&apos;Fizz&apos;&lt;/span&gt;
    &lt;b&gt;else&lt;/b&gt;:
        &lt;b&gt;return&lt;/b&gt; i

​

&lt;b&gt;for&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; range(&lt;span class=n&gt;1&lt;/span&gt;, &lt;span class=n&gt;101&lt;/span&gt;):
    print(fizz_buzz(i))
&lt;/code&gt;&lt;/pre&gt;
		&lt;/figure&gt;
	&lt;/div&gt;
&lt;/figure&gt;
&lt;p&gt;We now have an extra layer of encapsulation around it which demonstrates clearly that the solution when we were producing a &lt;code&gt;&lt;b&gt;&amp;amp;str&lt;/b&gt;&lt;/code&gt; of hoisting the &lt;code&gt;String&lt;/code&gt; variable declaration &lt;code&gt;x&lt;/code&gt; to the loop won’t work, because that variable would be going out of scope also, being contained inside the function. (&lt;a href=&quot;https://play.rust-lang.org/?code=fn%20main%28%29%20{ %0Afn%20fizz_buzz%28i%3A%20i32%29%20-%3E%20%26%27help_what_should_this_be%20str%20{ %0A%20%20%20%20let%20x%3B%0A%20%20%20%20if%20i%20%25%2015%20%3D%3D%200%20{ %0A%20%20%20%20%20%20%20%20%22FizzBuzz%22%0A%20%20%20%20}%20else%20if%20i%20%25%205%20%3D%3D%200%20{ %0A%20%20%20%20%20%20%20%20%22Buzz%22%0A%20%20%20%20}%20else%20if%20i%20%25%203%20%3D%3D%200%20{ %0A%20%20%20%20%20%20%20%20%22Fizz%22%0A%20%20%20%20}%20else%20{ %0A%20%20%20%20%20%20%20%20x%20%3D%20i.to_string%28%29%3B%0A%20%20%20%20%20%20%20%20%26%2Ax%0A%20%20%20%20}%0A}%0A%0Afor%20i%20in%201..101%20{ %0A%20%20%20%20println!%28%22{}%22%20%2C%20fizz_buzz%28i%29%29%3B%0A}%0A}&amp;run=1&quot;&gt;Try it if you’re not sure&lt;/a&gt;; the return type is unrepresentable in Rust’s type system, as there is no suitable lifetime—​&lt;code&gt;x&lt;/code&gt; won’t live for &lt;code&gt;&lt;b class=s&gt;&lt;i&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&lt;/code&gt; (the duration of the process) and there’s nothing else to tie it to.)
&lt;p&gt;And so, simply because we’ve put it in a function, we have a little inefficiency—​we’re allocating new strings for multiples of three or five when it shouldn’t be necessary.
&lt;h2&gt;Enter &lt;code&gt;Cow&amp;lt;&lt;b&gt;str&lt;/b&gt;&amp;gt;&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;Fortunately, Rust has algebraic data types (known as &lt;em&gt;enums&lt;/em&gt; in the language), and there’s a convenient type defined in the standard library as something that is either a string slice or an owned string.
&lt;p&gt;Here are the relevant definitions (without any of the methods that make it more useful):
&lt;figure id=figure-8&gt;
	&lt;pre&gt;&lt;code&gt;&lt;b&gt;pub enum&lt;/b&gt; Cow&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;, B: ?&lt;b&gt;Sized&lt;/b&gt; + &lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt; &lt;b&gt;where&lt;/b&gt; B: ToOwned {
    Borrowed(&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; B),
    Owned(&amp;lt;B &lt;b&gt;as&lt;/b&gt; ToOwned&amp;gt;::Owned)
}

&lt;b&gt;impl&lt;/b&gt; ToOwned &lt;b&gt;for str&lt;/b&gt; {
    &lt;b&gt;type&lt;/b&gt; Owned = String;

    &lt;b&gt;fn&lt;/b&gt; to_owned(&lt;b&gt;&amp;amp;self&lt;/b&gt;) -&amp;gt; String {
        …
    }
}
&lt;/code&gt;&lt;/pre&gt;
	&lt;figcaption&gt;
		&lt;p&gt;&lt;strong&gt;Figure 8:&lt;/strong&gt; the &lt;a href=https://doc.rust-lang.org/std/borrow/enum.Cow.html&gt;&lt;code&gt;std::borrow::Cow&lt;/code&gt;&lt;/a&gt; definition and how &lt;code&gt;Cow&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&lt;/span&gt;, &lt;b&gt;str&lt;/b&gt;&amp;gt;&lt;/code&gt;&lt;soft-br&gt;&lt;/soft-br&gt; comes from that.&lt;/p&gt;

		&lt;p&gt;The &lt;code&gt;ToOwned&lt;/code&gt; implementation is defined in &lt;code&gt;library/alloc/src/str.rs&lt;/code&gt; in the Rust repository, if you’re interested; but it doesn’t really matter.&lt;/i&gt;
		&lt;p&gt;And lo! Lifetime syntax makes an appearance.
	&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;I’ll admit that to be somewhat opaque to the inexperienced, so let’s fill in the generics to get an idea of approximately what it ends up for real life:
&lt;figure id=figure-9&gt;
	&lt;pre&gt;&lt;code&gt;&lt;b&gt;pub enum&lt;/b&gt; Cow&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;, &lt;b&gt;str&lt;/b&gt;&amp;gt; {
    Borrowed(&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; &lt;b&gt;str&lt;/b&gt;),
    Owned(String),
}
&lt;/code&gt;&lt;/pre&gt;
	&lt;figcaption&gt;
		&lt;p&gt;&lt;strong&gt;Figure 9:&lt;/strong&gt; an approximation of &lt;code&gt;Cow&amp;lt;&lt;b&gt;str&lt;/b&gt;&amp;gt;&lt;/code&gt;.

		&lt;p&gt;(This is for demonstration purposes only;&lt;soft-br&gt;&lt;/soft-br&gt; the grammar is not correct.)
	&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Now the particular type that we wish to pay attention to is &lt;code&gt;Cow&amp;lt;&lt;b class=s&gt;&lt;i&gt;&apos;static&lt;/i&gt;&lt;/b&gt;, &lt;b&gt;str&lt;/b&gt;&amp;gt;&lt;/code&gt;, which is either a &lt;code&gt;&lt;b&gt;&amp;amp;&lt;i class=s&gt;&apos;static&lt;/i&gt; str&lt;/b&gt;&lt;/code&gt; or a &lt;code&gt;String&lt;/code&gt;, and which dereferences to &lt;code&gt;&lt;b&gt;str&lt;/b&gt;&lt;/code&gt; [&lt;code&gt;Cow&amp;lt;B&amp;gt;&lt;/code&gt; implements &lt;a href=https://doc.rust-lang.org/std/borrow/enum.Cow.html#method.deref&gt;&lt;code&gt;Deref&amp;lt;Target = B&amp;gt;&lt;/code&gt;&lt;/a&gt;; put another way, given a &lt;code&gt;Cow&amp;lt;&lt;b&gt;str&lt;/b&gt;&amp;gt;&lt;/code&gt; &lt;code&gt;x&lt;/code&gt;, &lt;code&gt;&lt;b&gt;&amp;amp;*&lt;/b&gt;x&lt;/code&gt; produces a &lt;code&gt;&lt;b&gt;&amp;amp;str&lt;/b&gt;&lt;/code&gt; and you can mostly just treat a &lt;code&gt;Cow&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;, &lt;b&gt;str&lt;/b&gt;&amp;gt;&lt;/code&gt; as a &lt;code&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&lt;b&gt; str&lt;/b&gt;&lt;/code&gt;.]). Why is this type so interesting for us? Because it is completely owned data, containing no non‐&lt;code&gt;&lt;b class=s&gt;&lt;i&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&lt;/code&gt; lifetimes. In other words, if we create one of these inside a function, it is entirely self‐contained, not having any references to things inside the function and we can return it without any trouble. Expressed even more sloppily: this is a type that can contain a string literal, or an owned string that you have constructed.
&lt;p&gt;For assistance in creating these objects, there are implementations of &lt;a href=https://doc.rust-lang.org/std/convert/trait.From.html&gt;&lt;code&gt;From&lt;/code&gt;&lt;/a&gt; for &lt;code&gt;Cow&amp;lt;&lt;b&gt;str&lt;/b&gt;&amp;gt;&lt;/code&gt;; thanks to these, if you have a &lt;code&gt;&lt;b&gt;&amp;amp;str&lt;/b&gt;&lt;/code&gt; &lt;em&gt;or&lt;/em&gt; a &lt;code&gt;String&lt;/code&gt;, you can write &lt;code&gt;Cow::from(x)&lt;/code&gt; or, where it can be inferred that the result must be &lt;code&gt;Cow&amp;lt;&lt;b&gt;str&lt;/b&gt;&amp;gt;&lt;/code&gt;, &lt;code&gt;x.into()&lt;/code&gt;, instead of having to write the specific enum variant, &lt;code&gt;Cow::Borrowed(x)&lt;/code&gt; or &lt;code&gt;Cow::Owned(x)&lt;/code&gt;.
&lt;p&gt;As mentioned, &lt;code&gt;Cow&amp;lt;&lt;b&gt;str&lt;/b&gt;&amp;gt;&lt;/code&gt; dereferences to &lt;code&gt;&lt;b&gt;str&lt;/b&gt;&lt;/code&gt;, allowing us to very often treat it as though it were a &lt;code&gt;&lt;b&gt;&amp;amp;str&lt;/b&gt;&lt;/code&gt;. A prime example of this is the manner in which we can use it directly in string formatting, using that type’s &lt;code&gt;std::fmt::Display&lt;/code&gt; implementation with the &lt;code&gt;&lt;b class=s&gt;{}&lt;/b&gt;&lt;/code&gt; format string (&lt;code&gt;fmt::Display&lt;/code&gt; is the direct parallel of &lt;code&gt;__str__()&lt;/code&gt; in Python’s string formatting, or &lt;code&gt;to_s()&lt;/code&gt;, &lt;code&gt;toString()&lt;/code&gt;, &lt;i&gt;&amp;amp;c.&lt;/i&gt; in various other languages, though it works directly with a writer allowing you to skip the writing to an intermediate string if you want; the &lt;a href=https://doc.rust-lang.org/std/string/trait.ToString.html#tymethod.to_string&gt;&lt;code&gt;to_string()&lt;/code&gt;&lt;/a&gt; method on any type implementing &lt;code&gt;fmt::Display&lt;/code&gt; uses this mechanism to produce a &lt;code&gt;String&lt;/code&gt;).
&lt;p&gt;Here’s what it looks like:
&lt;figure id=figure-10&gt;
	&lt;pre&gt;&lt;code&gt;&lt;mark&gt;&lt;b&gt;use&lt;/b&gt; std::borrow::Cow;&lt;/mark&gt;

&lt;b&gt;fn&lt;/b&gt; fizz_buzz(i: &lt;b&gt;i32&lt;/b&gt;) -&amp;gt; &lt;mark&gt;Cow&amp;lt;&lt;b class=s&gt;&lt;i&gt;&apos;static&lt;/i&gt;&lt;/b&gt;, &lt;b&gt;str&lt;/b&gt;&amp;gt;&lt;/mark&gt; {
    &lt;b&gt;if&lt;/b&gt; i % &lt;span class=n&gt;15&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;FizzBuzz&quot;&lt;/span&gt;&lt;mark&gt;.into()&lt;/mark&gt;
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;5&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;Buzz&quot;&lt;/span&gt;&lt;mark&gt;.into()&lt;/mark&gt;
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;3&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;span class=s&gt;&quot;Fizz&quot;&lt;/span&gt;&lt;mark&gt;.into()&lt;/mark&gt;
    } &lt;b&gt;else&lt;/b&gt; {
        i.to_string()&lt;mark&gt;.into()&lt;/mark&gt;
    }
}

&lt;b&gt;for&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; &lt;span class=n&gt;1&lt;/span&gt;..&lt;span class=n&gt;101&lt;/span&gt; {
    &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;&lt;b&gt;{}&lt;/b&gt;&quot;&lt;/span&gt;, fizz_buzz(i));
}
&lt;/code&gt;&lt;/pre&gt;
	&lt;figcaption&gt;
		&lt;p&gt;&lt;strong&gt;Figure 10:&lt;/strong&gt; a FizzBuzz function returning &lt;a href=https://doc.rust-lang.org/std/borrow/enum.Cow.html&gt;&lt;code&gt;Cow&amp;lt;&lt;b class=s&gt;&lt;i&gt;&apos;static&lt;/i&gt;&lt;/b&gt;, &lt;b&gt;str&lt;/b&gt;&amp;gt;&lt;/code&gt;&lt;/a&gt;: this works.&lt;/p&gt;
	&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Great! We’ve reduced the work the computer needs to do and made our admittedly trivial case faster.
&lt;p&gt;But can we go further?
&lt;h2&gt;Writing our own enum and implementing&lt;soft-br&gt;&lt;/soft-br&gt; &lt;code&gt;std::fmt::Display&lt;/code&gt; efficiently&lt;/h2&gt;
&lt;p&gt;Of course, what we’re representing for each term in the sequence isn’t actually “a static string slice or an owned string”, it’s “‘Fizz’, ‘Buzz’, ‘FizzBuzz’ or a number”. We just converted all the choices to strings eagerly; we could just as easily make it lazy, avoiding the extra allocation where possible (and in fact they are &lt;em&gt;all&lt;/em&gt; avoidable).
&lt;p&gt;Let’s make an enum of our own, which we’ll call &lt;code&gt;Term&lt;/code&gt;.
&lt;p&gt;While we’re at it, we’ll implement &lt;code&gt;std::fmt::Display&lt;/code&gt;, which means that we can print to stdout without even needing to create the intermediate &lt;code&gt;String&lt;/code&gt;. We’ll also implement &lt;code&gt;std::fmt::Debug&lt;/code&gt;, which answers to the format string &lt;code&gt;&lt;b class=s&gt;{:?}&lt;/b&gt;&lt;/code&gt; and is for giving a developer-oriented representation of the object, akin to Python’s &lt;code&gt;__repr__()&lt;/code&gt; and Ruby’s &lt;code&gt;inspect&lt;/code&gt;; it can be just the same thing in this case.
&lt;figure id=figure-11&gt;
	&lt;figcaption class=with-captioned-subfigure&gt;
		&lt;p&gt;&lt;strong&gt;Figure 11:&lt;/strong&gt; using a dedicated data type to&lt;soft-br&gt;&lt;/soft-br&gt; represent the &lt;em&gt;real&lt;/em&gt; possibilities efficiently.
		&lt;p&gt;The suggested Python code is thoroughly contrived, as is going to be the case in all languages without algebraic data types; I provide it for the sake of users not familiar with algebraic data types to at least give an &lt;em&gt;impression&lt;/em&gt; of how it works.
	&lt;/figcaption&gt;
	&lt;div class=line-between&gt;
		&lt;figure&gt;
			&lt;figcaption&gt;Rust&lt;/figcaption&gt;
			&lt;pre&gt;&lt;code&gt;&lt;b&gt;use&lt;/b&gt; std::fmt;

&lt;b&gt;enum&lt;/b&gt; Term {
    Fizz,
    Buzz,
    FizzBuzz,
    Number(&lt;b&gt;i32&lt;/b&gt;),
}

&lt;b&gt;impl&lt;/b&gt; fmt::Display &lt;b&gt;for&lt;/b&gt; Term {
    &lt;b&gt;fn&lt;/b&gt; fmt(&lt;b&gt;&amp;amp;self&lt;/b&gt;, f: &lt;b&gt;&amp;amp;mut&lt;/b&gt; fmt::Formatter) -&amp;gt; fmt::Result {
        &lt;b&gt;match *&lt;/b&gt;self {
            Term::Fizz =&amp;gt; f.write_str(&lt;span class=s&gt;&quot;Fizz&quot;&lt;/span&gt;),
            Term::Buzz =&amp;gt; f.write_str(&lt;span class=s&gt;&quot;Buzz&quot;&lt;/span&gt;),
            Term::FizzBuzz =&amp;gt; f.write_str(&lt;span class=s&gt;&quot;FizzBuzz&quot;&lt;/span&gt;),
            Term::Number(num) =&amp;gt; &lt;i&gt;write!&lt;/i&gt;(f, &lt;span class=s&gt;&quot;&lt;b&gt;{}&lt;/b&gt;&quot;&lt;/span&gt;, num),
        }
    }
}

&lt;b&gt;impl&lt;/b&gt; fmt::Debug &lt;b&gt;for&lt;/b&gt; Term {
    &lt;b&gt;fn&lt;/b&gt; fmt(&lt;b&gt;&amp;amp;self&lt;/b&gt;, f: &lt;b&gt;&amp;amp;mut&lt;/b&gt; fmt::Formatter) -&amp;gt; fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

&lt;b&gt;fn&lt;/b&gt; fizz_buzz(i: &lt;b&gt;i32&lt;/b&gt;) -&amp;gt; Term {
    &lt;b&gt;if&lt;/b&gt; i % &lt;span class=n&gt;15&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        Term::FizzBuzz
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;5&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        Term::Buzz
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;3&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        Term::Fizz
    } &lt;b&gt;else&lt;/b&gt; {
        Term::Number(i)
    }
}

&lt;b&gt;for&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; &lt;span class=n&gt;1&lt;/span&gt;..&lt;span class=n&gt;101&lt;/span&gt; {
    &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;&lt;b&gt;{}&lt;/b&gt;&quot;&lt;/span&gt;, fizz_buzz(i));
}
&lt;/code&gt;&lt;/pre&gt;
		&lt;/figure&gt;

		&lt;figure&gt;
			&lt;figcaption&gt;Python analogue (thoroughly contrived)&lt;/figcaption&gt;
			&lt;pre&gt;&lt;code&gt;&lt;b&gt;class&lt;/b&gt; Term:

    &lt;b&gt;def&lt;/b&gt; __init__(self, value):
        self._value = value

    &lt;b&gt;def&lt;/b&gt; __str__(self):
        &lt;b&gt;if&lt;/b&gt; self &lt;b&gt;is&lt;/b&gt; Term.Fizz:
            &lt;b&gt;return&lt;/b&gt; &lt;span class=s&gt;&quot;Fizz&quot;&lt;/span&gt;
        &lt;b&gt;elif&lt;/b&gt; self &lt;b&gt;is&lt;/b&gt; Term.Buzz:
            &lt;b&gt;return&lt;/b&gt; &lt;span class=s&gt;&quot;Buzz&quot;&lt;/span&gt;
        &lt;b&gt;elif&lt;/b&gt; self &lt;b&gt;is&lt;/b&gt; Term.FizzBuzz:
            &lt;b&gt;return&lt;/b&gt; &lt;span class=s&gt;&quot;FizzBuzz&quot;&lt;/span&gt;
        &lt;b&gt;else&lt;/b&gt;:
            &lt;b&gt;return&lt;/b&gt; str(self._value)

    &lt;b&gt;def&lt;/b&gt; __repr__(self):
        &lt;b&gt;return&lt;/b&gt; str(self)

    &lt;i&gt;&lt;b&gt;@&lt;/b&gt;staticmethod&lt;/i&gt;
    &lt;b&gt;def&lt;/b&gt; Number(number):
        &lt;b&gt;return&lt;/b&gt; Term(number)

&lt;i class=c&gt;# Pretend that these are opaque&lt;/i&gt;
Term.Fizz = Term(object())
Term.Buzz = Term(object())
Term.FizzBuzz = Term(object())

&lt;b&gt;def&lt;/b&gt; fizz_buzz(i):
    &lt;b&gt;if&lt;/b&gt; i % &lt;span class=n&gt;15&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt;:
        &lt;b&gt;return&lt;/b&gt; Term.FizzBuzz
    &lt;b&gt;elif&lt;/b&gt; i % &lt;span class=n&gt;5&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt;:
        &lt;b&gt;return&lt;/b&gt; Term.Buzz
    &lt;b&gt;elif&lt;/b&gt; i % &lt;span class=n&gt;3&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt;:
        &lt;b&gt;return&lt;/b&gt; Term.Fizz
    &lt;b&gt;else&lt;/b&gt;:
        &lt;b&gt;return&lt;/b&gt; Term.Number(i)

&lt;b&gt;for&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; range(&lt;span class=n&gt;1&lt;/span&gt;, &lt;span class=n&gt;101&lt;/span&gt;):
    print(fizz_buzz(i))
&lt;/code&gt;&lt;/pre&gt;
		&lt;/figure&gt;
	&lt;/div&gt;
&lt;/figure&gt;
&lt;p&gt;Observe also that this is doing a really good job of actually representing the data contained, though for this trivial case it wouldn’t matter much if it didn’t. We could just as easily have replaced the first three variants of that enum with a single &lt;code&gt;Word(&lt;b&gt;&amp;amp;&lt;i class=s&gt;&apos;static&lt;/i&gt; str&lt;/b&gt;)&lt;/code&gt; variant, using &lt;code&gt;Word(&lt;span class=s&gt;&quot;FizzBuzz&quot;&lt;/span&gt;)&lt;/code&gt; &lt;i&gt;et al.&lt;/i&gt; for the values. (In fact, that was actually the first version I wrote of this step of the process—​see, even I was fixed on using strings where it’s simply unnecessary!)
&lt;p&gt;We could go further, showing how to write a dedicated iterator, but with how Rust’s iterator chaining works, this isn’t really necessary—​you can just write &lt;code&gt;(&lt;span class=n&gt;1&lt;/span&gt;..&lt;span class=n&gt;101&lt;/span&gt;).map(fizz_buzz)&lt;/code&gt;. That gives a lot more flexibility; as soon as you have something implementing &lt;code&gt;Iterator&amp;lt;Item = &lt;b&gt;i32&lt;/b&gt;&amp;gt;&lt;/code&gt;, you can just tack &lt;code&gt;.map(fizz_buzz)&lt;/code&gt; onto the end of it and you have a type implementing &lt;code&gt;Iterator&amp;lt;Item = Term&amp;gt;&lt;/code&gt;.
&lt;p&gt;That loop could be rewritten in this style, incidentally:
&lt;figure id=figure-12&gt;
	&lt;figcaption class=with-captioned-subfigure&gt;
		&lt;p&gt;&lt;strong&gt;Figure 12:&lt;/strong&gt; mapping an integer iterator&lt;soft-br&gt;&lt;/soft-br&gt; to the &lt;code&gt;fizz_buzz&lt;/code&gt; function.
	&lt;/figcaption&gt;
	&lt;div class=line-between&gt;
		&lt;figure&gt;
			&lt;figcaption&gt;Rust&lt;/figcaption&gt;
			&lt;pre&gt;&lt;code&gt;&lt;b&gt;for&lt;/b&gt; f &lt;b&gt;in&lt;/b&gt; (&lt;span class=n&gt;1&lt;/span&gt;..&lt;span class=n&gt;101&lt;/span&gt;).map(fizz_buzz) {
    &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;&lt;b&gt;{}&lt;/b&gt;&quot;&lt;/span&gt;, f);
}
&lt;/code&gt;&lt;/pre&gt;
		&lt;/figure&gt;

		&lt;figure&gt;
			&lt;figcaption&gt;Python&lt;/figcaption&gt;
			&lt;pre&gt;&lt;code&gt;&lt;b&gt;for&lt;/b&gt; f &lt;b&gt;in&lt;/b&gt; map(fizz_buzz, range(&lt;span class=n&gt;1&lt;/span&gt;, &lt;span class=n&gt;101&lt;/span&gt;)):
    print(f)
&lt;/code&gt;&lt;/pre&gt;
		&lt;/figure&gt;
	&lt;/div&gt;
&lt;/figure&gt;
&lt;p&gt;Whichever of these sorts of ways we choose to do it, we end up with the good ol’ FizzBuzz lines:
&lt;figure&gt;
&lt;pre style=max-height:20em;overflow-y:auto&gt;&lt;code&gt;1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz&lt;/code&gt;&lt;/pre&gt;
&lt;/figure&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;So now you have it: why your first FizzBuzz implementation in Rust might not work. Some of the difficult parts of it are typical of statically typed languages, and some more of them are more specific to Rust. (As a matter of fact, the situation would be similar in C++, but C++ lets you do all sorts of silly things and doesn’t give much in the way of memory safety. Don’t bother arguing with &lt;em&gt;me&lt;/em&gt; on that point though, I’m just going off the word of others—​I don’t know C++ especially well.&lt;!-- Of course, this pretense of ignorance will affect nothing. Some will still complain about it. But at least it’s someone else I’m causing trouble for, for I have disclaimed ownership of the problem 😛. --&gt;)
&lt;p&gt;We’ve covered how Rust’s ownership model can prevent you from writing things in certain ways that you might be used to, and why (though not the concrete benefits of doing this); also how Rust is able to express more efficient concepts; we’ve seen how enums (algebraic data types) can be used to model data more precisely and efficiently.
&lt;p&gt;Hopefully you’ve seen the power of this and it interests you.
&lt;p&gt;Is this an increased conceptual burden? Yes.
&lt;p&gt;Is it a nuisance? Occasionally. (My experience is that it saves trouble at least as often as it causes it.)
&lt;p&gt;Does it allow you to improve your program’s efficiency? Certainly, and with complete confidence. While in the past these things have required a loss of certainty about safety and correctness properties, in Rust you don’t need to make it a tradeoff.
&lt;p&gt;Does it make code easier to reason about? In simple cases like this you won’t see that, but these general attributes of the ownership model and algebraic data types really do help in more complex cases. (I really miss these things when working in Python.)
&lt;p&gt;These matters end up both a good thing and a bad thing about Rust; sometimes you will love them, and occasionally you will hate them. But I at least don’t hate them often at all.
&lt;p&gt;Should you use Rust? Well, I would suggest that you at least try it if you haven’t. You may well find it not ready or fit for your purposes. Because of its focus on systems development, it &lt;em&gt;is&lt;/em&gt; more cumbersome for many higher‐level tasks, though even on those it can be surprisingly effective.
&lt;p&gt;Finally, if you’re not familiar with Rust or got lost at any point, I suggest you go through the &lt;a href=https://doc.rust-lang.org/&gt;official documentation&lt;/a&gt;; the &lt;a href=https://doc.rust-lang.org/book/&gt;Rust book&lt;/a&gt; has sections dealing with lifetimes and ownership, enums and a whole lot more. I also wrote &lt;a href=../rust-ownership-the-hard-way/&gt;Rust ownership the hard way&lt;/a&gt;, an article that you may find helpful in understanding this crucial defining feature of Rust. If you still have questions, places like &lt;a href=irc://irc.mozilla.org/#rust-beginners&gt;#rust-beginners on irc.mozilla.org&lt;/a&gt; are great. (Pretty much everyone agrees that the Rust community is superb. You &lt;em&gt;will&lt;/em&gt; get good answers there.)
&lt;h2&gt;Appendix: other FizzBuzz techniques&lt;/h2&gt;
&lt;p&gt;This section is by no means comprehensive, but includes a few extras that have been pointed out over time.
&lt;h3&gt;1. &lt;code&gt;&lt;b&gt;match&lt;/b&gt;&lt;/code&gt; instead of &lt;code&gt;&lt;b&gt;if&lt;/b&gt;&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;People often suggest replacing the chained conditionals with a &lt;code&gt;&lt;b&gt;match&lt;/b&gt;&lt;/code&gt; block, which incidentally lets you skip the “superfluous” &lt;code&gt;i % &lt;span class=n&gt;15&lt;/span&gt;&lt;/code&gt;:
&lt;figure id=figure-13&gt;
	&lt;pre&gt;&lt;code&gt;&lt;b&gt;for&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; &lt;span class=n&gt;1&lt;/span&gt;..&lt;span class=n&gt;101&lt;/span&gt; {
    &lt;b&gt;match&lt;/b&gt; (i % &lt;span class=n&gt;3&lt;/span&gt;, i % &lt;span class=n&gt;5&lt;/span&gt;) {
        (&lt;span class=n&gt;0&lt;/span&gt;, &lt;span class=n&gt;0&lt;/span&gt;) =&gt; &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;FizzBuzz&quot;&lt;/span&gt;),
        (_, &lt;span class=n&gt;0&lt;/span&gt;) =&gt; &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;Buzz&quot;&lt;/span&gt;),
        (&lt;span class=n&gt;0&lt;/span&gt;, _) =&gt; &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;Fizz&quot;&lt;/span&gt;),
        (_, _) =&gt; &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;&lt;b&gt;{}&lt;/b&gt;&quot;&lt;/span&gt;, i),
    }
}&lt;/code&gt;&lt;/pre&gt;
	&lt;figcaption&gt;
		&lt;p&gt;&lt;strong&gt;Figure 13:&lt;/strong&gt; &lt;a href=#figure-1&gt;Figure 1&lt;/a&gt;, but with &lt;code&gt;&lt;b&gt;match&lt;/b&gt;&lt;/code&gt;&lt;soft-br&gt;&lt;/soft-br&gt; instead of chained &lt;code&gt;&lt;b&gt;if&lt;/b&gt;&lt;/code&gt;.
		&lt;p&gt;Application of this technique to other examples is left as an exercise for the reader.
	&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;Opinions differ on which is nicer. In this &lt;em&gt;particular&lt;/em&gt; case I personally prefer the &lt;code&gt;&lt;b&gt;if&lt;/b&gt;&lt;/code&gt; version, but if you introduced a third word I’d switch to the &lt;code&gt;&lt;b&gt;match&lt;/b&gt;&lt;/code&gt; version.
&lt;h3&gt;2. &lt;code&gt;std::fmt::Display&lt;/code&gt; trait objects&lt;/h3&gt;
&lt;p&gt;This possibility was brought to my attention in September 2019, sitting somewhere between the code in &lt;a href=#figure-2&gt;Figure 2&lt;/a&gt; and the code in &lt;a href=#figure-11&gt;Figure 11&lt;/a&gt;, by using a dynamic trait object:
&lt;figure id=figure-14&gt;
	&lt;pre&gt;&lt;code&gt;&lt;b&gt;for&lt;/b&gt; i &lt;b&gt;in&lt;/b&gt; &lt;span class=n&gt;1&lt;/span&gt;..&lt;span class=n&gt;101&lt;/span&gt; {
    &lt;b&gt;let&lt;/b&gt; result&lt;mark&gt;: &lt;b&gt;&amp;amp;dyn&lt;/b&gt; std::fmt::Display&lt;/mark&gt; = &lt;b&gt;if&lt;/b&gt; i % &lt;span class=n&gt;15&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;mark&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;/mark&gt;&lt;span class=s&gt;&quot;FizzBuzz&quot;&lt;/span&gt;
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;5&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;mark&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;/mark&gt;&lt;span class=s&gt;&quot;Buzz&quot;&lt;/span&gt;
    } &lt;b&gt;else if&lt;/b&gt; i % &lt;span class=n&gt;3&lt;/span&gt; == &lt;span class=n&gt;0&lt;/span&gt; {
        &lt;mark&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;/mark&gt;&lt;span class=s&gt;&quot;Fizz&quot;&lt;/span&gt;
    } &lt;b&gt;else&lt;/b&gt; {
        &lt;mark&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;/mark&gt;i
    };
    &lt;i&gt;println!&lt;/i&gt;(&lt;span class=s&gt;&quot;&lt;b&gt;{}&lt;/b&gt;&quot;&lt;/span&gt;, result);
}
&lt;/code&gt;&lt;/pre&gt;
	&lt;figcaption&gt;
		&lt;p&gt;&lt;strong&gt;Figure 14:&lt;/strong&gt; making &lt;a href=#figure-2&gt;Figure 2&lt;/a&gt; work by the use of &lt;code&gt;std::fmt::Display&lt;/code&gt; trait objects.
		&lt;p&gt;Application of this technique to &lt;soft-br&gt;&lt;/soft-br&gt;other examples is again left as &lt;soft-br&gt;&lt;/soft-br&gt;an exercise for the reader.
	&lt;/figcaption&gt;
&lt;/figure&gt;
&lt;p&gt;This is a worthwhile technique to be aware of: if there exists a trait that covers the required functionality shared between the types you wish to store in the one variable, a dynamic trait object can be a viable option instead of making your own enum. If you wanted to be able to inspect the values to determine what they semantically were, this would be insufficient, and something like the &lt;code&gt;Term&lt;/code&gt; enum would be called for, but so long as all you want to do is format them for display, a &lt;code&gt;std::fmt::Display&lt;/code&gt; trait object is fine.
&lt;h3&gt;3. And if you really like fiddling with FizzBuzz optimisation…&lt;/h3&gt;
&lt;p&gt;&lt;a href=https://old.reddit.com/r/rust/comments/27ziqs/some_issue_regarding_obsolete_tilde_syntax/ci5xlrq&gt;Feel free.&lt;/a&gt; Here’s the final conclusion of that lot, updated to compile now, plus making &lt;code&gt;OUT&lt;/code&gt; a byte string for improved legibility (!?):
&lt;figure id=figure-15&gt;
	&lt;pre&gt;&lt;code&gt;&lt;i&gt;#![no_std]&lt;/i&gt;
&lt;i&gt;#![feature(lang_items, start, rustc_private)]&lt;/i&gt;

&lt;b&gt;extern crate&lt;/b&gt; libc;

&lt;b&gt;static&lt;/b&gt; OUT: [&lt;b&gt;u8&lt;/b&gt;; &lt;span class=n&gt;413&lt;/span&gt;] = *&lt;span class=s&gt;b&quot;&lt;b&gt;&lt;i&gt;\&lt;/i&gt;&lt;/b&gt;
    1&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;2&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;4&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Buzz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;7&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;8&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Buzz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;11&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;13&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;14&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;FizzBuzz&lt;b&gt;&lt;i&gt;\n\&lt;/i&gt;&lt;/b&gt;
    16&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;17&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;19&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Buzz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;22&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;23&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Buzz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;26&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;28&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;29&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;FizzBuzz&lt;b&gt;&lt;i&gt;\n\&lt;/i&gt;&lt;/b&gt;
    31&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;32&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;34&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Buzz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;37&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;38&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Buzz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;41&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;43&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;44&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;FizzBuzz&lt;b&gt;&lt;i&gt;\n\&lt;/i&gt;&lt;/b&gt;
    46&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;47&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;49&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Buzz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;52&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;53&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Buzz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;56&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;58&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;59&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;FizzBuzz&lt;b&gt;&lt;i&gt;\n\&lt;/i&gt;&lt;/b&gt;
    61&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;62&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;64&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Buzz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;67&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;68&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Buzz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;71&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;73&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;74&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;FizzBuzz&lt;b&gt;&lt;i&gt;\n\&lt;/i&gt;&lt;/b&gt;
    76&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;77&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;79&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Buzz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;82&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;83&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Buzz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;86&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;88&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;89&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;FizzBuzz&lt;b&gt;&lt;i&gt;\n\&lt;/i&gt;&lt;/b&gt;
    91&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;92&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;94&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Buzz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;97&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;98&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Fizz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;Buzz&lt;b&gt;&lt;i&gt;\n&lt;/i&gt;&lt;/b&gt;&quot;&lt;/span&gt;;

&lt;i&gt;#[start]&lt;/i&gt;
&lt;b&gt;fn&lt;/b&gt; start(_argc: &lt;b&gt;isize&lt;/b&gt;, _argv: &lt;b&gt;*const *const u8&lt;/b&gt;) -&gt; &lt;b&gt;isize&lt;/b&gt; {
    &lt;b&gt;unsafe&lt;/b&gt; {
        core::arch::&lt;i&gt;asm!&lt;/i&gt;(
            &lt;span class=s&gt;&quot;syscall&quot;&lt;/span&gt;,
            in(&lt;span class=s&gt;&quot;rax&quot;&lt;/span&gt;) &lt;span class=n&gt;1&lt;/span&gt;, &lt;i class=c&gt;// syscall number = write&lt;/i&gt;
            in(&lt;span class=s&gt;&quot;rdi&quot;&lt;/span&gt;) &lt;span class=n&gt;1&lt;/span&gt;, &lt;i class=c&gt;// fd = stdout&lt;/i&gt;
            in(&lt;span class=s&gt;&quot;rsi&quot;&lt;/span&gt;) OUT.as_ptr(),
            in(&lt;span class=s&gt;&quot;rdx&quot;&lt;/span&gt;) OUT.len(),
            out(&lt;span class=s&gt;&quot;rcx&quot;&lt;/span&gt;) _,
            out(&lt;span class=s&gt;&quot;r11&quot;&lt;/span&gt;) _,
            lateout(&lt;span class=s&gt;&quot;rax&quot;&lt;/span&gt;) _,
        );
    }
    &lt;span class=n&gt;0&lt;/span&gt;
}

&lt;i&gt;#[lang = &lt;span class=s&gt;&quot;eh_personality&quot;&lt;/span&gt;]&lt;/i&gt; &lt;b&gt;extern fn&lt;/b&gt; eh_personality() {}
&lt;i&gt;#[panic_handler]&lt;/i&gt; &lt;b&gt;extern fn&lt;/b&gt; panic_handler(_: &lt;b&gt;&amp;amp;&lt;/b&gt;core::panic::PanicInfo) -&gt; &lt;b&gt;!&lt;/b&gt; { &lt;b&gt;loop&lt;/b&gt; {} }
&lt;/code&gt;&lt;/pre&gt;
	&lt;figcaption&gt;
		&lt;p&gt;&lt;strong&gt;Figure 15:&lt;/strong&gt; optimising the FizzBuzz problem roughly as far as humanly possible.
		&lt;p&gt;Applying this technique should be left unexercised by the reader: it’s provided for demonstration purposes only, and should not be attempted at home or at work.
		&lt;p&gt;(This code depends on Linux syscall conventions, so it won’t work on other platforms.)
	&lt;/figcaption&gt;
&lt;/figure&gt;

			&lt;aside class=trailer&gt;
		&lt;hr&gt;
		&lt;p&gt;Comments? Questions? Corrections? If you want to contact me about anything in this post, email me at &lt;a href=&quot;mailto:me@chrismorgan.info&quot;&gt;me@chrismorgan.info&lt;/a&gt;.
	&lt;/aside&gt;
		</content>
	</entry>
	<entry xml:base="https://chrismorgan.info/blog/teepee-design-method/">
		<title type="html">Teepee design: the HTTP method</title>
		<published>2014-07-08T00:00:00+00:00</published>
		<updated>2014-07-08T00:00:00+00:00</updated>
		<link href="https://chrismorgan.info/blog/teepee-design-method/" type="text/html"/>
		<id>http://chrismorgan.info/blog/teepee-design-method.html</id>
		<category scheme="https://chrismorgan.info/blog/tags/" term="web" label="Web" />
		<category scheme="https://chrismorgan.info/blog/tags/" term="rust" label="Rust" />
		<category scheme="https://chrismorgan.info/blog/tags/" term="teepee" label="Teepee" />
		<content type="html">
			&lt;p class=intro&gt;Now we come to the &lt;code&gt;Method&lt;/code&gt; type. While there are a few improvements to be made, this is one of the things that probably can’t be significantly improved on over rust-http.
			&lt;p&gt;&lt;em&gt;This article is part of the series on &lt;a href=/blog/introducing-teepee/&gt;the rust-http redesign, Teepee&lt;/a&gt;.&lt;/em&gt;
&lt;h2&gt;An apology&lt;/h2&gt;
&lt;p&gt;Teepee has stood with nothing much happening for a while; this is my fault and I’m sorry to have caused it. Things are starting moving again and will continue moving now; I have the low‐level design of the HTTP/1 message reading parts of Teepee almost done and expect to post this within a few days. But I don’t blame you if you don’t trust my “few days”; I wouldn’t either.
&lt;p&gt;There are also quite a number of people that have emailed me asking how you can help on Teepee—​sorry, it’s a little hard to figure out ways just at present, for the project is not really mature enough for that yet. It will come, though. If you really want fun, start looking at HTTP/2 and figure out a sensible implementation strategy, especially for its stream dependencies and prioritisation…
&lt;p&gt;Unless stated otherwise, all grammar comes from &lt;a href=https://tools.ietf.org/html/rfc7230 title=&quot;Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing&quot;&gt;RFC 7230&lt;/a&gt;.
&lt;h2&gt;Relevant definitions&lt;/h2&gt;
&lt;p&gt;Here’s what rust-http has:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;pub enum&lt;/b&gt; Method {
    Options,
    Get,
    Head,
    Post,
    Put,
    Delete,
    Trace,
    Connect,
    Patch,  &lt;i class=c&gt;// RFC 5789&lt;/i&gt;
    ExtensionMethod(String),
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;Here is what RFC 2616 had:
&lt;figure&gt;&lt;blockquote&gt;&lt;pre&gt;   The Method  token indicates the method to be performed on the
   resource identified by the Request-URI. The method is case-sensitive.

       Method         = &quot;OPTIONS&quot;                ; Section 9.2
                      | &quot;GET&quot;                    ; Section 9.3
                      | &quot;HEAD&quot;                   ; Section 9.4
                      | &quot;POST&quot;                   ; Section 9.5
                      | &quot;PUT&quot;                    ; Section 9.6
                      | &quot;DELETE&quot;                 ; Section 9.7
                      | &quot;TRACE&quot;                  ; Section 9.8
                      | &quot;CONNECT&quot;                ; Section 9.9
                      | extension-method
       extension-method = token&lt;/pre&gt;&lt;/blockquote&gt;&lt;/figure&gt;
&lt;p&gt;Here is what RFC 7230 has:
&lt;figure&gt;&lt;blockquote&gt;&lt;pre&gt;   The method token indicates the request method to be performed on the
   target resource.  The request method is case-sensitive.

     method         = token

   The request methods defined by this specification can be found in
   Section 4 of [RFC7231], along with information regarding the HTTP
   method registry and considerations for defining new methods.&lt;/pre&gt;&lt;/blockquote&gt;&lt;/figure&gt;
&lt;p&gt;The contents of RFC 7231 are largely immaterial here, except insofar as the common properties that are defined for methods are specified (in &lt;a href=https://tools.ietf.org/html/rfc7231#section-8.1.1&gt;section 8.1.1&lt;/a&gt;): these are &lt;em&gt;safety&lt;/em&gt; and &lt;em&gt;idempotency&lt;/em&gt;. Representing these properties seem to me desirable.
&lt;h2&gt;The &lt;code&gt;token&lt;/code&gt; type&lt;/h2&gt;
&lt;p&gt;By the way, if you’re wondering what characters are valid in a method, &lt;code&gt;method = token&lt;/code&gt;; &lt;code&gt;token = 1*tchar&lt;/code&gt;; &lt;code&gt;tchar =  &quot;!&quot; / &quot;#&quot; / &quot;$&quot; / &quot;%&quot; / &quot;&amp;amp;&quot; / &quot;&apos;&quot; / &quot;*&quot; / &quot;+&quot; / &quot;-&quot; / &quot;.&quot; / &quot;^&quot; / &quot;_&quot; / &quot;`&quot; / &quot;|&quot; / &quot;~&quot; / DIGIT / ALPHA&lt;/code&gt;.
&lt;p&gt;In other words, a method (or any other place we get &lt;code&gt;token&lt;/code&gt; in the grammar) is a sequence of letters, numbers or any of those other fancy characters—​yes, &lt;code&gt;!#$%&amp;amp;&apos;*+-.^_`|~&lt;/code&gt; is a valid HTTP method name.
&lt;p&gt;This is the sort of thing that should probably be encoded in the type system, using a separate token type instead of using &lt;code&gt;String&lt;/code&gt; or &lt;code&gt;Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;&lt;/code&gt;, &lt;code&gt;&lt;b&gt;&amp;amp;str&lt;/b&gt;&lt;/code&gt; or &lt;code&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;[&lt;b&gt;u8&lt;/b&gt;]&lt;/code&gt;. Given this much, we will need both owned and borrowed versions of this, for I am imposing a rule in the low‐level API that it must not allocate, while causing the token to be owned is the only sensible route for the higher‐level API.
&lt;p&gt;The solution is an equivalent to &lt;code&gt;std::str::MaybeOwned&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt;&lt;/code&gt;, which applies to strings and is an owned string or a string slice (possibly even of static duration): then the owned form can be &lt;code&gt;MaybeOwnedToken&amp;lt;&lt;b&gt;&lt;i class=s&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&amp;gt;&lt;/code&gt;, and the unowned form &lt;code&gt;MaybeOwnedToken&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt;&lt;/code&gt;. (Incidentally, we &lt;em&gt;really&lt;/em&gt; need a general solution to this problem.)
&lt;p&gt;On second thoughts, I doubt that the owned and slice tokens will be considered of value by themselves, so we might just eliminate them altogether, putting them straight into the enum.
&lt;p&gt;Here’s the gist of what it’ll end up as:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;pub enum&lt;/b&gt; Token&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt; {
    Owned {
        &lt;i&gt;#[doc(hidden)]&lt;/i&gt;
        &lt;b&gt;pub&lt;/b&gt; _bytes: Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;,
    },
    Slice {
        &lt;i&gt;#[doc(hidden)]&lt;/i&gt;
        &lt;b&gt;pub&lt;/b&gt; _bytes: &lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; [&lt;b&gt;u8&lt;/b&gt;],
    },
}

&lt;b&gt;impl&lt;/b&gt;&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt; Token&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt; {
    &lt;b&gt;fn&lt;/b&gt; bytes&amp;lt;&lt;i class=s&gt;&apos;b&lt;/i&gt;&amp;gt;(&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;b&lt;/i&gt; &lt;b&gt;self&lt;/b&gt;) -&amp;gt; &lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;b&lt;/i&gt; [&lt;b&gt;u8&lt;/b&gt;];
    &lt;b&gt;fn&lt;/b&gt; into_owned(&lt;b&gt;self&lt;/b&gt;) -&amp;gt; Token&amp;lt;&lt;b&gt;&lt;i class=s&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&amp;gt;;
    &lt;b&gt;fn&lt;/b&gt; as_slice&amp;lt;&lt;i class=s&gt;&apos;b&lt;/i&gt;&amp;gt;(&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;b&lt;/i&gt; &lt;b&gt;self&lt;/b&gt;) -&amp;gt; Token&amp;lt;&lt;i class=s&gt;&apos;b&lt;/i&gt;&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;(The &lt;code&gt;&lt;i&gt;#[doc(hidden)]&lt;/i&gt; &lt;b&gt;pub&lt;/b&gt;&lt;/code&gt; part is to allow statics to be defined outside the defining module. You know, we really need a general solution to this problem also.)
&lt;p&gt;While a little cumbersome, unifying these imposes certain constraints on the solution space for handling methods.
&lt;h2&gt;Design one: a struct and statics&lt;/h2&gt;
&lt;p&gt;Nothing like a bit of code.
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;pub struct&lt;/b&gt; Method&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt; {
    name: Token&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt;,
    safe: &lt;b&gt;bool&lt;/b&gt;,
    idempotent: &lt;b&gt;bool&lt;/b&gt;,
}

&lt;b&gt;pub static&lt;/b&gt; GET: Method&amp;lt;&lt;b&gt;&lt;i class=s&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&amp;gt; = Method {
    name: token::Slice { _bytes: &lt;span class=s&gt;b&quot;GET&quot;&lt;/span&gt;, },
    safe: &lt;b&gt;true&lt;/b&gt;,
    idempotent: &lt;b&gt;true&lt;/b&gt;,
};
&lt;i class=c&gt;// Et cetera.&lt;/i&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;&lt;code&gt;Method::from_token&lt;/code&gt; would then produce one of those statics where possible, thus automatically filling in the details with regards to safety and idempotency, which are important to model. (I don’t think I clarified this earlier; well, I have seen too much code comparing method names in an ad‐hoc way, where what they &lt;em&gt;really&lt;/em&gt; wanted to be examining was whether the method was safe or idempotent.)
&lt;p&gt;This looks very well, doesn’t it? Unfortunately, it simply won’t do because of its ergonomics. Because of how we unified the token type, &lt;em&gt;&lt;code&gt;Method&amp;lt;&apos;static&amp;gt;&lt;/code&gt; is no longer &lt;code&gt;Copy&lt;/code&gt;&lt;/em&gt;, and something like &lt;code&gt;request.method = GET&lt;/code&gt; will not work—​can’t move out of static. We are left with &lt;code&gt;request.method = GET.clone()&lt;/code&gt;, and the hypothetical &lt;code&gt;request(url, GET.clone())&lt;/code&gt;, a construct which is all in all rather an untidy thing. Is this a reasonable trade‐off to make? I am not convinced it is.
&lt;!-- &lt;p&gt;Of course, if we discard the notion of the unification of token types and keep the split between owned and slice—​if, in fact, we were at the low level to give out a token for the method, rather than a &lt;code&gt;Method&lt;/code&gt;—​well then, we would be In Business. --&gt;&lt;!-- I *think* that comment is not correct any more. --&gt;
&lt;h2&gt;Design two: back to the enum&lt;/h2&gt;
&lt;p&gt;The second option is a mere extension of what is in rust-http: simple variants (which avoids the &lt;code&gt;Copy&lt;/code&gt; problem) plus one at the end for custom things. Something like this:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;i&gt;macro_rules!&lt;/i&gt; method_enum {
    (&lt;span class=m&gt;$(&lt;/span&gt;
        &lt;span class=m&gt;$ident:ident&lt;/span&gt;
        &lt;span class=m&gt;$bytes:expr&lt;/span&gt;
        &lt;span class=m&gt;$safe:ident&lt;/span&gt;
        &lt;span class=m&gt;$idempotent:ident&lt;/span&gt;
        &lt;i&gt;#[&lt;span class=m&gt;$doc:meta&lt;/span&gt;]&lt;/i&gt;;
    &lt;span class=m&gt;)*&lt;/span&gt;) =&amp;gt; {
        &lt;b&gt;&lt;i class=c&gt;/// …&lt;/i&gt;&lt;/b&gt;
        &lt;b&gt;pub enum&lt;/b&gt; Method&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt; {
            &lt;span class=m&gt;$(&lt;/span&gt;&lt;i&gt;#[&lt;span class=m&gt;$doc&lt;/span&gt;]&lt;/i&gt; &lt;b&gt;pub&lt;/b&gt; &lt;span class=m&gt;$ident&lt;/span&gt;,&lt;span class=m&gt;)*&lt;/span&gt;
            &lt;b&gt;&lt;i class=c&gt;/// A method not in the IANA HTTP method registry.&lt;/i&gt;&lt;/b&gt;
            &lt;b&gt;pub&lt;/b&gt; UnregisteredMethod {
                token: Token&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt;,
                safe: &lt;b&gt;bool&lt;/b&gt;,
                idempotent: &lt;b&gt;bool&lt;/b&gt;,
            },
        }

        &lt;b&gt;impl&lt;/b&gt; Method {
            &lt;b&gt;pub fn&lt;/b&gt; token(&lt;b&gt;&amp;amp;self&lt;/b&gt;) -&amp;gt; Token&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt; {
                &lt;b&gt;match *&lt;/b&gt;self {
                    &lt;span class=m&gt;$(&lt;/span&gt;&lt;span class=m&gt;$ident&lt;/span&gt; =&amp;gt; SliceToken { _bytes: &lt;span class=m&gt;$bytes&lt;/span&gt; },&lt;span class=m&gt;)*&lt;/span&gt;
                    UnregisteredMethod =&amp;gt; token.as_slice(),
                }
            }
            &lt;i class=c&gt;// &amp;amp;c. for safe and idempotent&lt;/i&gt;
        }
    }
}

&lt;samp&gt;&lt;i&gt;method_enum!&lt;/i&gt; {
    &lt;i class=c&gt;// Variant name   method name          safe  idempotent&lt;/i&gt;
    Acl               &lt;span class=s&gt;b&quot;ACL&quot;&lt;/span&gt;               &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`ACL`, defined in RFC3744, Section 8.1&quot;&lt;/span&gt;]&lt;/i&gt;;
    BaselineControl   &lt;span class=s&gt;b&quot;BASELINE-CONTROL&quot;&lt;/span&gt;  &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`BASELINE-CONTROL`, defined in RFC3253, Section 12.6&quot;&lt;/span&gt;]&lt;/i&gt;;
    Bind              &lt;span class=s&gt;b&quot;BIND&quot;&lt;/span&gt;              &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`BIND`, defined in RFC5842, Section 4&quot;&lt;/span&gt;]&lt;/i&gt;;
    Checkin           &lt;span class=s&gt;b&quot;CHECKIN&quot;&lt;/span&gt;           &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`CHECKIN`, defined in RFC3253, Section 4.4, Section 9.4&quot;&lt;/span&gt;]&lt;/i&gt;;
    Checkout          &lt;span class=s&gt;b&quot;CHECKOUT&quot;&lt;/span&gt;          &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`CHECKOUT`, defined in RFC3253, Section 4.3, Section 8.8&quot;&lt;/span&gt;]&lt;/i&gt;;
    Connect           &lt;span class=s&gt;b&quot;CONNECT&quot;&lt;/span&gt;           &lt;b&gt;false false&lt;/b&gt; &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`CONNECT`, defined in RFC7231, Section 4.3.6&quot;&lt;/span&gt;]&lt;/i&gt;;
    Copy              &lt;span class=s&gt;b&quot;COPY&quot;&lt;/span&gt;              &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`COPY`, defined in RFC4918, Section 9.8&quot;&lt;/span&gt;]&lt;/i&gt;;
    Delete            &lt;span class=s&gt;b&quot;DELETE&quot;&lt;/span&gt;            &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`DELETE`, defined in RFC7231, Section 4.3.5&quot;&lt;/span&gt;]&lt;/i&gt;;
    Get               &lt;span class=s&gt;b&quot;GET&quot;&lt;/span&gt;               &lt;b&gt;true  true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`GET`, defined in RFC7231, Section 4.3.1&quot;&lt;/span&gt;]&lt;/i&gt;;
    Head              &lt;span class=s&gt;b&quot;HEAD&quot;&lt;/span&gt;              &lt;b&gt;true  true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`HEAD`, defined in RFC7231, Section 4.3.2&quot;&lt;/span&gt;]&lt;/i&gt;;
    Label             &lt;span class=s&gt;b&quot;LABEL&quot;&lt;/span&gt;             &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`LABEL`, defined in RFC3253, Section 8.2&quot;&lt;/span&gt;]&lt;/i&gt;;
    Link              &lt;span class=s&gt;b&quot;LINK&quot;&lt;/span&gt;              &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`LINK`, defined in RFC2068, Section 19.6.1.2&quot;&lt;/span&gt;]&lt;/i&gt;;
    Lock              &lt;span class=s&gt;b&quot;LOCK&quot;&lt;/span&gt;              &lt;b&gt;false false&lt;/b&gt; &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`LOCK`, defined in RFC4918, Section 9.10&quot;&lt;/span&gt;]&lt;/i&gt;;
    Merge             &lt;span class=s&gt;b&quot;MERGE&quot;&lt;/span&gt;             &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`MERGE`, defined in RFC3253, Section 11.2&quot;&lt;/span&gt;]&lt;/i&gt;;
    MkActivity        &lt;span class=s&gt;b&quot;MKACTIVITY&quot;&lt;/span&gt;        &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`MKACTIVITY`, defined in RFC3253, Section 13.5&quot;&lt;/span&gt;]&lt;/i&gt;;
    MkCalendar        &lt;span class=s&gt;b&quot;MKCALENDAR&quot;&lt;/span&gt;        &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`MKCALENDAR`, defined in RFC4791, Section 5.3.1&quot;&lt;/span&gt;]&lt;/i&gt;;
    MkCol             &lt;span class=s&gt;b&quot;MKCOL&quot;&lt;/span&gt;             &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`MKCOL`, defined in RFC4918, Section 9.3&quot;&lt;/span&gt;]&lt;/i&gt;;
    MkRedirectRef     &lt;span class=s&gt;b&quot;MKREDIRECTREF&quot;&lt;/span&gt;     &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`MKREDIRECTREF`, defined in RFC4437, Section 6&quot;&lt;/span&gt;]&lt;/i&gt;;
    MkWorkspace       &lt;span class=s&gt;b&quot;MKWORKSPACE&quot;&lt;/span&gt;       &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`MKWORKSPACE`, defined in RFC3253, Section 6.3&quot;&lt;/span&gt;]&lt;/i&gt;;
    Move              &lt;span class=s&gt;b&quot;MOVE&quot;&lt;/span&gt;              &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`MOVE`, defined in RFC4918, Section 9.9&quot;&lt;/span&gt;]&lt;/i&gt;;
    Options           &lt;span class=s&gt;b&quot;OPTIONS&quot;&lt;/span&gt;           &lt;b&gt;true  true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`OPTIONS`, defined in RFC7231, Section 4.3.7&quot;&lt;/span&gt;]&lt;/i&gt;;
    OrderPatch        &lt;span class=s&gt;b&quot;ORDERPATCH&quot;&lt;/span&gt;        &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`ORDERPATCH`, defined in RFC3648, Section 7&quot;&lt;/span&gt;]&lt;/i&gt;;
    Patch             &lt;span class=s&gt;b&quot;PATCH&quot;&lt;/span&gt;             &lt;b&gt;false false&lt;/b&gt; &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`PATCH`, defined in RFC5789, Section 2&quot;&lt;/span&gt;]&lt;/i&gt;;
    Post              &lt;span class=s&gt;b&quot;POST&quot;&lt;/span&gt;              &lt;b&gt;false false&lt;/b&gt; &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`POST`, defined in RFC7231, Section 4.3.3&quot;&lt;/span&gt;]&lt;/i&gt;;
    PropFind          &lt;span class=s&gt;b&quot;PROPFIND&quot;&lt;/span&gt;          &lt;b&gt;true  true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`PROPFIND`, defined in RFC4918, Section 9.1&quot;&lt;/span&gt;]&lt;/i&gt;;
    PropPatch         &lt;span class=s&gt;b&quot;PROPPATCH&quot;&lt;/span&gt;         &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`PROPPATCH`, defined in RFC4918, Section 9.2&quot;&lt;/span&gt;]&lt;/i&gt;;
    Put               &lt;span class=s&gt;b&quot;PUT&quot;&lt;/span&gt;               &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`PUT`, defined in RFC7231, Section 4.3.4&quot;&lt;/span&gt;]&lt;/i&gt;;
    Rebind            &lt;span class=s&gt;b&quot;REBIND&quot;&lt;/span&gt;            &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`REBIND`, defined in RFC5842, Section 6&quot;&lt;/span&gt;]&lt;/i&gt;;
    Report            &lt;span class=s&gt;b&quot;REPORT&quot;&lt;/span&gt;            &lt;b&gt;true  true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`REPORT`, defined in RFC3253, Section 3.6&quot;&lt;/span&gt;]&lt;/i&gt;;
    Search            &lt;span class=s&gt;b&quot;SEARCH&quot;&lt;/span&gt;            &lt;b&gt;true  true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`SEARCH`, defined in RFC5323, Section 2&quot;&lt;/span&gt;]&lt;/i&gt;;
    Trace             &lt;span class=s&gt;b&quot;TRACE&quot;&lt;/span&gt;             &lt;b&gt;true  true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`TRACE`, defined in RFC7231, Section 4.3.8&quot;&lt;/span&gt;]&lt;/i&gt;;
    Unbind            &lt;span class=s&gt;b&quot;UNBIND&quot;&lt;/span&gt;            &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`UNBIND`, defined in RFC5842, Section 5&quot;&lt;/span&gt;]&lt;/i&gt;;
    Uncheckout        &lt;span class=s&gt;b&quot;UNCHECKOUT&quot;&lt;/span&gt;        &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`UNCHECKOUT`, defined in RFC3253, Section 4.5&quot;&lt;/span&gt;]&lt;/i&gt;;
    Unlink            &lt;span class=s&gt;b&quot;UNLINK&quot;&lt;/span&gt;            &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`UNLINK`, defined in RFC2068, Section 19.6.1.3&quot;&lt;/span&gt;]&lt;/i&gt;;
    Unlock            &lt;span class=s&gt;b&quot;UNLOCK&quot;&lt;/span&gt;            &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`UNLOCK`, defined in RFC4918, Section 9.11&quot;&lt;/span&gt;]&lt;/i&gt;;
    Update            &lt;span class=s&gt;b&quot;UPDATE&quot;&lt;/span&gt;            &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`UPDATE`, defined in RFC3253, Section 7.1&quot;&lt;/span&gt;]&lt;/i&gt;;
    UpdateRedirectRef &lt;span class=s&gt;b&quot;UPDATEREDIRECTREF&quot;&lt;/span&gt; &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`UPDATEREDIRECTREF`, defined in RFC4437, Section 7&quot;&lt;/span&gt;]&lt;/i&gt;;
    VersionControl    &lt;span class=s&gt;b&quot;VERSION-CONTROL&quot;&lt;/span&gt;   &lt;b&gt;false true&lt;/b&gt;  &lt;i&gt;#[doc = &lt;span class=s&gt;&quot;`VERSION-CONTROL`, defined in RFC3253, Section 3.5&quot;&lt;/span&gt;]&lt;/i&gt;;
}&lt;/samp&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;Incidentally, Teepee will support &lt;a href=https://www.iana.org/assignments/http-methods/http-methods.xhtml&gt;all the methods in the IANA HTTP method registry&lt;/a&gt;.
&lt;p&gt;This has in its favour that it is something that has good ergonomics for the standard case. It does, however, have a slight weakness in that when a new method is added to the registry, code that was already using it &lt;em&gt;may&lt;/em&gt; break, depending on how things were done. Pattern matching may break, for example. But this is a rare thing, so I’m not terribly distressed about it. It does, however, stand against it—​strict semver would require a new major release to add a new item to the method enum.
&lt;h2&gt;Summary&lt;/h2&gt;
&lt;p&gt;In the end, I think that what rust-http does at present is sound; it just needs to be expanded to cover the entire HTTP method registry, and expanded to also keep track of whether a method is safe and/or idempotent.
&lt;p&gt;Pending a suitable outcome to &lt;a href=https://www.reddit.com/r/rust/comments/2a46wb/teepee_design_the_http_method/&gt;discussion on Reddit&lt;/a&gt;, the second approach is what I intend to implement.
&lt;!--&lt;h2&gt;By the way…&lt;/h2&gt;

&lt;p&gt;I’m open for freelance work, especially with regards to Rust (though I guess most of the people reading this are more interested in writing thier own code than paying me to write code!). I also appreciate donations to help with working on these things: &lt;a href=https://www.paypal.com/cgi-bin/webscr?cmd=_donations&amp;amp;business=me%40chrismorgan.info&amp;amp;item_name=Teepee&gt;PayPal&lt;/a&gt;, &lt;a href=bitcoin:14NcYrmxFCN9wAHhxCHkyt4PU9bqnveBUj&gt;Bitcoin&lt;/a&gt; (14NcYrmxFCN9wAHhxCHkyt4PU9bqnveBUj), &lt;a href=https://gittip.com/chris-morgan&gt;Gittip&lt;/a&gt;.--&gt;

			&lt;aside class=trailer&gt;
		&lt;hr&gt;
		&lt;p&gt;Comments? Questions? Corrections? If you want to contact me about anything in this post, email me at &lt;a href=&quot;mailto:me@chrismorgan.info&quot;&gt;me@chrismorgan.info&lt;/a&gt;.
	&lt;/aside&gt;
		</content>
	</entry>
	<entry xml:base="https://chrismorgan.info/blog/teepee-design-header-representation/">
		<title type="html">Teepee design: header representation</title>
		<published>2014-05-10T00:00:00+00:00</published>
		<updated>2014-05-10T00:00:00+00:00</updated>
		<link href="https://chrismorgan.info/blog/teepee-design-header-representation/" type="text/html"/>
		<id>http://chrismorgan.info/blog/teepee-design-header-representation.html</id>
		<category scheme="https://chrismorgan.info/blog/tags/" term="web" label="Web" />
		<category scheme="https://chrismorgan.info/blog/tags/" term="rust" label="Rust" />
		<category scheme="https://chrismorgan.info/blog/tags/" term="teepee" label="Teepee" />
		<content type="html">
			&lt;p class=intro&gt;Header representation is a critical matter to Teepee’s design: it is uncompromisingly strongly typed, but there must be tradeoffs. After trying quite a few different schemes at length, I have settled upon quite a novel scheme which I believe to optimally balance all considerations.
			&lt;p&gt;&lt;em&gt;This article is part of the series on &lt;a href=/blog/introducing-teepee/&gt;the rust-http redesign, Teepee&lt;/a&gt;.&lt;/em&gt;
&lt;p class=summary&gt;Header representation is a critical matter to Teepee’s design: it is uncompromisingly strongly typed, but there must be tradeoffs. After trying quite a few different schemes at length, I have settled upon quite a novel scheme which I believe to optimally balance all considerations.
&lt;h2&gt;The current situation&lt;/h2&gt;
&lt;p&gt;Here’s how rust-http currently handles headers:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;struct&lt;/b&gt; HeaderCollection {
    &lt;i class=c&gt;// … plenty of strongly typed headers …&lt;/i&gt;
    connection: Option&amp;lt;Vec&amp;lt;Connection&amp;gt;&amp;gt;,
    content_type: Option&amp;lt;MediaType&amp;gt;,
    &lt;i class=c&gt;// … plenty more s.t. headers … and then at the end:&lt;/i&gt;
    extensions: HashMap&amp;lt;StrBuf, StrBuf&amp;gt;
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;… and then the header collection is placed into the request or response struct as the &lt;code&gt;headers&lt;/code&gt; field. Thus the value of the &lt;code&gt;Content-Length&lt;/code&gt; header of a response is &lt;code&gt;response.headers.content_length&lt;/code&gt; and is of type &lt;code&gt;Option&amp;lt;uint&amp;gt;&lt;/code&gt;. Note also that the request and response have different header collections, as there are various headers appropriate only to a request or response.
&lt;p&gt;At present, headers are parsed proactively; valid headers are placed in a &lt;code&gt;Some&lt;/code&gt; value and invalid or missing values are stored as &lt;code&gt;None&lt;/code&gt;.
&lt;h2&gt;Criteria&lt;/h2&gt;
&lt;p&gt;There are a few criteria that I considered for header design in Teepee:
&lt;ol&gt;
    &lt;li&gt;&lt;p&gt;Performance must be “good”.
    &lt;li&gt;&lt;p&gt;Ergonomics for using standardised headers must be “good”.
    &lt;li&gt;&lt;p&gt;Ergonomics for using extension headers must be “good”.
    &lt;li&gt;&lt;p&gt;Extension headers should be strongly typed.
    &lt;li&gt;&lt;p&gt;Badly formatted headers must be accessible in &lt;em&gt;some&lt;/em&gt; way.
    &lt;li&gt;&lt;p&gt;A shared access technique for both standardised and extension headers is desirable (for backwards compatibility as more headers are added to the Teepee libraries), especially if it allows headers to be used as multiple types.
&lt;/ol&gt;
&lt;h2&gt;A sample of schemes tried&lt;/h2&gt;
&lt;h3&gt;Bad header field value handling&lt;/h3&gt;
&lt;p&gt;For various reasons, it is necessary that invalid headers be able to be accessed, though normally an illegal value should be dropped. This was not done at all in rust-http, but is essential in Teepee. (For more fun, there are certain things to be aware of in parsing headers like that there may be multiple fields with the same name, but only if they would be equivalent to a single comma-separated list, with the difference that any illegal items should be dropped, or that in some cases &lt;em&gt;part&lt;/em&gt; of a field may be invalid and be dropped while the rest is interpreted.)
&lt;ol&gt;
    &lt;li&gt;&lt;p&gt;Use a &lt;code&gt;Option&amp;lt;Result&amp;lt;T, Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/code&gt; (or similar) type instead of &lt;code&gt;Option&amp;lt;T&amp;gt;&lt;/code&gt;. Rejected outright for (a) bad ergonomics, for almost no one can do anything with malformed values, so normal code must not be burdened with it; and (b) because partially bad headers would be lost.

    &lt;li&gt;&lt;p&gt;Expose the unparsed values through callbacks that can be injected, or a conditions‐like scheme (minus the fail‐by‐default behaviour). Rejected because while the raw values can be accessed, doing so will be excessively difficult, leading to complaints when people do actually want it, as the layer or framework they are using may not have exposed it in an accessible way.

    &lt;li&gt;&lt;p&gt;Store raw headers alongside the main place; for example, given &lt;code&gt;request.headers&lt;/code&gt;, have &lt;code&gt;request.raw_headers&lt;/code&gt; or &lt;code&gt;request.headers.raw&lt;/code&gt; as a &lt;code&gt;HashMap&amp;lt;Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;, Vec&amp;lt;Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/code&gt; (that is, a mapping of field names to the values for that field) or a &lt;code&gt;Vec&amp;lt;(Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;, Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;)&amp;gt;&lt;/code&gt; (that is, all of the header fields, completely raw). (Try saying “vec” ten times rapidly.) This isn’t ideal for the overhead, as it requires two heap allocations for each header field (the lowest level will still operate without allocations there; this is purely a feature of the high level) and must still store each header in raw form.
&lt;/ol&gt;
&lt;p&gt;Of the options shown here, the last is probably the best. I have one further objection to it, though: it makes it &lt;em&gt;too&lt;/em&gt; easy to access those raw values. I’m afraid that if I put that there, people might use it (!), and I don’t want that. (Yes, I’m stubborn about all this; I want to give people what’s good for them, not necessarily what they want. We’ll find out if I’m right in the years to come.) This can be remedied by having the raw fields private and only exposed through unsafe functions.
&lt;p&gt;There is one other scheme, building upon the concepts of the third option, where the handling of bad header fields falls quite naturally out of the solution for header storage; I omit that here is it will be expanded upon later.
&lt;h3&gt;Header storage&lt;/h3&gt;
&lt;p&gt;I shall not bore you with the full details, though I have plenty more details should you be interested; here is a smattering of some of the things I’ve considered:
&lt;ol&gt;
    &lt;li&gt;&lt;p&gt;&lt;strong&gt;Fields for standard headers, a &lt;code&gt;Map&amp;lt;StrBuf, StrBuf&amp;gt;&lt;/code&gt; for the rest:&lt;/strong&gt; (a.k.a. “leave it as it is”) great performance, great ergonomics for standard headers, but extension headers are very much second class citizens, being weakly typed.

    &lt;li&gt;&lt;p&gt;&lt;strong&gt;Fields for known headers, drop (or &lt;code&gt;Map&lt;/code&gt;) unknown headers, multiple inheritance edition:&lt;/strong&gt; very cool and perfect in almost every way… except the wait for a feature that will probably never be implemented.

    &lt;li&gt;&lt;p&gt;&lt;strong&gt;Fields for known headers, drop (or &lt;code&gt;Map&lt;/code&gt;) unknown headers, say‐what‐you‐want edition:&lt;/strong&gt; (require people to declare the headers they expect to deal with and their types, producing a struct for each case). Great performance, poor ergonomics of declaration (especially for its unfamiliarity), useless for code reuse.

    &lt;li&gt;&lt;p&gt;&lt;strong&gt;The other thing I’m about to talk about:&lt;/strong&gt; good enough performance, good ergonomics for all headers, treats all headers alike; flawless with regards to backwards compatibility; allows read and write access to raw headers where necessary.

    &lt;li&gt;&lt;p&gt;&lt;strong&gt;A combination of fields for standard headers with that thing I’m about to talk about for the rest:&lt;/strong&gt; gets better performance for standard headers, but at the cost of consistency, future‐proofing and raw access to standard headers. (In short, a cute idea but not worth it.)
&lt;/ol&gt;
&lt;h2&gt;The scheme I have settled on&lt;/h2&gt;
&lt;p&gt;This scheme is not perfect, but weighing up the advantages and disadvantages I am fairly confident that it is fairly optimal for Rust.
&lt;p&gt;Here are some examples of the API we end up with. We get nice and easy typed access:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;headers.get(CONNECTION); &lt;i class=c&gt;// -&amp;gt; Option&amp;lt;Vec&amp;lt;Connection&amp;gt;&amp;gt;&lt;/i&gt;
headers.get_ref(LOCATION); &lt;i class=c&gt;// -&amp;gt; Option&amp;lt;&amp;amp;url::Url&amp;gt;&lt;/i&gt;
headers.get_mut_ref(DATE); &lt;i class=c&gt;// -&amp;gt; Option&amp;lt;&amp;amp;mut time::Tm&amp;gt;&lt;/i&gt;
headers.set(LOCATION, url &lt;i class=c&gt;/* url::Url */&lt;/i&gt;);
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;(&lt;code&gt;get()&lt;/code&gt; necessarily takes &lt;code&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;mut self&lt;/code&gt;, so you can’t borrow more than one header at a time—​that’s a large part of why &lt;code&gt;get&lt;/code&gt; is there, which clones the object before returning it.)
&lt;p&gt;It would be possible to expose raw values via unsafe functions…
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;unsafe&lt;/b&gt; {
    headers.get_raw(&lt;span class=s&gt;&quot;connection&quot;&lt;/span&gt;); &lt;i class=c&gt;// -&amp;gt; Option&amp;lt;&amp;amp;[Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;]&amp;gt;&lt;/i&gt;
    headers.set_raw(&lt;span class=s&gt;&quot;connection&quot;&lt;/span&gt;,
                    &lt;i&gt;vec!&lt;/i&gt;(Vec::from_slice(&lt;i&gt;bytes!&lt;/i&gt;(&lt;span class=s&gt;&quot;close&quot;&lt;/span&gt;))));
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;But that’s actually not necessary! We can use &lt;code&gt;get&lt;/code&gt; and &lt;code&gt;set&lt;/code&gt; with a different argument and, from that, a different return type:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;headers.get(raw(&lt;span class=s&gt;&quot;connection&quot;&lt;/span&gt;)); &lt;i class=c&gt;// -&amp;gt; Option&amp;lt;Vec&amp;lt;Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/i&gt;
headers.set(raw(&lt;span class=s&gt;&quot;connection&quot;&lt;/span&gt;),
            &lt;i&gt;vec!&lt;/i&gt;(Vec::from_slice(&lt;i&gt;bytes!&lt;/i&gt;(&lt;span class=s&gt;&quot;close&quot;&lt;/span&gt;))));
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;(This will be slower than exposing raw values directly, as it is treating &lt;code&gt;Vec&amp;lt;Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;&amp;gt;&lt;/code&gt; as a strong header type and so incurring an extra conversion; therefore in practice extra unsafe methods will probably be provided for raw access. But it demonstrates the principle of the thing.)
&lt;p&gt;And the good part—​it’s in there, so now we can access it as another strong type:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;i&gt;assert_eq!&lt;/i&gt;(headers.get(CONNECTION), Some(&lt;i&gt;vec!&lt;/i&gt;(Close)));&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;How is this done? Internally it maintains a hash map of values which may be either raw or &lt;code&gt;&lt;b&gt;Box&lt;/b&gt;&amp;lt;Header&amp;gt;&lt;/code&gt; (a trait object); initially everything is raw, but as you access them they are parsed into the appropriate header type and stored; if you try to access a value as a different type, it is converted to the HTTP wire format and then parsed as the new type, and stored if that succeeded.
&lt;p&gt;All this is pretty magic, and something that you couldn’t easily achieve in most languages, especially with regards to the type inference&lt;!-- I could insert a snide comment about Go here if I wanted to, but it’s not worth it—​too easy! --&gt;—​but it’s something that can be achieved in Rust in a very convenient and &lt;em&gt;completely safe&lt;/em&gt; way! (OK, so it takes just a smidgeon of unsafe code, implementing the &lt;code&gt;Any*Ext&lt;/code&gt; traits—​just a straight copy of the implementations for &lt;code&gt;&lt;b&gt;&amp;amp;&lt;/b&gt;Any&lt;/code&gt; et al. But the interface it exposes is absolutely solid and crash‐proof.)
&lt;h2&gt;A proof‐of‐concept implementation&lt;/h2&gt;
&lt;p&gt;I could yammer on and on about how it works, but I don’t think it’s necessary. Here’s my proof of concept in all its half‐baked glory:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;
&lt;b class=c&gt;&lt;i&gt;/// The data type of an HTTP header for encoding and decoding.&lt;/i&gt;&lt;/b&gt;
&lt;b&gt;pub trait&lt;/b&gt; Header: Any {
    &lt;b&gt;fn&lt;/b&gt; parse_header(s: &lt;b&gt;&amp;amp;&lt;/b&gt;[Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;]) -&amp;gt; Option&amp;lt;Self&amp;gt;;

    &lt;b class=c&gt;&lt;i&gt;/// Introducing an `Err` value that does *not* come from the writer is incorrect behaviour and&lt;/i&gt;&lt;/b&gt;
    &lt;b class=c&gt;&lt;i&gt;/// may lead to task failure in certain situations. (The primary case where this will happen is&lt;/i&gt;&lt;/b&gt;
    &lt;b class=c&gt;&lt;i&gt;/// accessing a cached Box&amp;lt;Header&amp;gt; object as a different type; then, it is shoved into a buffer&lt;/i&gt;&lt;/b&gt;
    &lt;b class=c&gt;&lt;i&gt;/// through fmt_header and then back into the new type through parse_header. Should the&lt;/i&gt;&lt;/b&gt;
    &lt;b class=c&gt;&lt;i&gt;/// fmt_header call have return an Err, it will fail.&lt;/i&gt;&lt;/b&gt;
    &lt;b&gt;fn&lt;/b&gt; fmt_header(&lt;b&gt;&amp;amp;self&lt;/b&gt;, f: &lt;b&gt;&amp;amp;mut&lt;/b&gt; fmt::Formatter) -&amp;gt; fmt::Result;
}

&lt;i class=c&gt;// I&apos;d prefer this as another trait with an implementation of Header for something satisfying that&lt;/i&gt;
&lt;i class=c&gt;// trait, but I can&apos;t do that because of those pesky &quot;conflicting implementations&quot; things.&lt;/i&gt;
&lt;i&gt;macro_rules!&lt;/i&gt; require_single_field {
    (&lt;span class=m&gt;$field_values:expr&lt;/span&gt;) =&amp;gt; ({
        &lt;b&gt;let mut&lt;/b&gt; iter = &lt;span class=m&gt;$field_values&lt;/span&gt;.iter();
        &lt;b&gt;match&lt;/b&gt; (iter.next(), iter.next()) {
            (Some(&lt;b&gt;ref&lt;/b&gt; field_value), None) =&amp;gt; field_value.as_slice(),
            _ =&amp;gt; &lt;b&gt;return&lt;/b&gt; None,
        }
    })
}

&lt;i class=c&gt;// impl copied from std::any. Not especially nice, sorry :-(&lt;/i&gt;
&lt;b&gt;impl&lt;/b&gt;&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt; AnyRefExt&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt; &lt;b&gt;for&lt;/b&gt; &lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; Header {
    &lt;i&gt;#[inline]&lt;/i&gt;
    &lt;b&gt;fn&lt;/b&gt; is&amp;lt;T: &lt;b&gt;&lt;i class=s&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&amp;gt;(&lt;b&gt;self&lt;/b&gt;) -&amp;gt; bool {
        &lt;b&gt;use&lt;/b&gt; std::intrinsics::TypeId;
        &lt;i class=c&gt;// Get TypeId of the type this function is instantiated with&lt;/i&gt;
        &lt;b&gt;let&lt;/b&gt; t = TypeId::of::&amp;lt;T&amp;gt;();

        &lt;i class=c&gt;// Get TypeId of the type in the trait object&lt;/i&gt;
        &lt;b&gt;let&lt;/b&gt; boxed = self.get_type_id();

        &lt;i class=c&gt;// Compare both TypeIds on equality&lt;/i&gt;
        t == boxed
    }

    &lt;i&gt;#[inline]&lt;/i&gt;
    &lt;b&gt;fn&lt;/b&gt; as_ref&amp;lt;T: &lt;b&gt;&lt;i class=s&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&amp;gt;(&lt;b&gt;self&lt;/b&gt;) -&amp;gt; Option&amp;lt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; T&amp;gt; {
        &lt;b&gt;if&lt;/b&gt; self.is::&amp;lt;T&amp;gt;() {
            Some(&lt;b&gt;unsafe&lt;/b&gt; { self.as_ref_unchecked() })
        } &lt;b&gt;else&lt;/b&gt; {
            None
        }
    }
}

&lt;b&gt;trait&lt;/b&gt; UncheckedAnyRefExt&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt; {
    &lt;b class=c&gt;&lt;i&gt;/// Returns a reference to the boxed value, assuming that it is of type `T`. This should only be&lt;/i&gt;&lt;/b&gt;
    &lt;b class=c&gt;&lt;i&gt;/// called if you are ABSOLUTELY CERTAIN of `T` as you will get really wacky output if it’s not.&lt;/i&gt;&lt;/b&gt;
    &lt;b&gt;unsafe fn&lt;/b&gt; as_ref_unchecked&amp;lt;T: &lt;b&gt;&lt;i class=s&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&amp;gt;(&lt;b&gt;self&lt;/b&gt;) -&amp;gt; &lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; T;
}

&lt;i class=c&gt;// Actually, I want to move this upstream. I have a patch ready which adds as_ref_unchecked,&lt;/i&gt;
&lt;i class=c&gt;// as_mut_unchecked and move_unchecked. What do you reckon? Opinions solicited. Of course, because&lt;/i&gt;
&lt;i class=c&gt;// this is Header rather than Any, I can&apos;t actually *use* such a thing myself if it&apos;s on Any...&lt;/i&gt;
&lt;b&gt;impl&lt;/b&gt;&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt; UncheckedAnyRefExt&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt; &lt;b&gt;for&lt;/b&gt; &lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; Header {
    &lt;i&gt;#[inline]&lt;/i&gt;
    &lt;b&gt;unsafe fn&lt;/b&gt; as_ref_unchecked&amp;lt;T: &lt;b&gt;&lt;i class=s&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&amp;gt;(self) -&amp;gt; &lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; T {
        &lt;b&gt;use&lt;/b&gt; std::raw::TraitObject;
        &lt;b&gt;use&lt;/b&gt; std::cast::{transmute, transmute_copy};

        &lt;i class=c&gt;// Get the raw representation of the trait object&lt;/i&gt;
        &lt;b&gt;let&lt;/b&gt; to: TraitObject = transmute_copy(&lt;b&gt;&amp;amp;&lt;/b&gt;self);

        &lt;i class=c&gt;// Extract the data pointer&lt;/i&gt;
        transmute(to.data)
    }
}

&lt;b&gt;trait&lt;/b&gt; UncheckedAnyMutRefExt&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt; {
    &lt;b class=c&gt;&lt;i&gt;/// Returns a reference to the boxed value, assuming that it is of type `T`. This should only be&lt;/i&gt;&lt;/b&gt;
    &lt;b class=c&gt;&lt;i&gt;/// called if you are ABSOLUTELY CERTAIN of `T` as you will get really wacky output if it’s not.&lt;/i&gt;&lt;/b&gt;
    &lt;b&gt;unsafe fn&lt;/b&gt; as_mut_unchecked&amp;lt;T: &lt;b&gt;&lt;i class=s&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&amp;gt;(&lt;b&gt;self&lt;/b&gt;) -&amp;gt; &lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; &lt;b&gt;mut&lt;/b&gt; T;
}

&lt;b&gt;impl&lt;/b&gt;&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt; UncheckedAnyMutRefExt&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt; &lt;b&gt;for &amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; &lt;b&gt;mut&lt;/b&gt; Header {
    &lt;i&gt;#[inline]&lt;/i&gt;
    &lt;b&gt;unsafe fn&lt;/b&gt; as_mut_unchecked&amp;lt;T: &lt;b&gt;&lt;i class=s&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&amp;gt;(&lt;b&gt;self&lt;/b&gt;) -&amp;gt; &lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; &lt;b&gt;mut&lt;/b&gt; T {
        &lt;b&gt;use&lt;/b&gt; std::raw::TraitObject;
        &lt;b&gt;use&lt;/b&gt; std::cast::{transmute, transmute_copy};

        &lt;i class=c&gt;// Get the raw representation of the trait object&lt;/i&gt;
        &lt;b&gt;let&lt;/b&gt; to: TraitObject = transmute_copy(&lt;b&gt;&amp;amp;&lt;/b&gt;self);

        &lt;i class=c&gt;// Extract the data pointer&lt;/i&gt;
        transmute(to.data)
    }
}

&lt;b class=c&gt;&lt;i&gt;/// Standard usage of this is a marker type, like this:
///
/// ```rust
/// // The header data type
/// pub struct Foo {
///     ...
/// }
///
/// impl Header for Foo {
///     ...
/// }
///
/// // The marker type for accessing the header and specifying the name
/// pub struct FOO;
///
/// impl HeaderMarker&amp;lt;Foo&amp;gt; for FOO {
///     fn header_name(&amp;amp;self) -&amp;gt; SendStr {
///         Slice(&quot;foo&quot;)
///     }
/// }
/// ```
///
/// Then, accessing the header is done like this:
///
/// ```rust
/// let foo = request.headers.get(FOO);
/// request.headers.set(FOO, foo);
/// ```
///
/// And lo! `foo` is a `Foo` object corresponding to the `foo` header in the request.
///
/// Authors are strongly advised that they should not implement `HeaderMarker&amp;lt;T&amp;gt;` for more than one
/// `T` on the same type.&lt;/i&gt;&lt;/b&gt;
&lt;b&gt;pub trait&lt;/b&gt; HeaderMarker&amp;lt;OutputType: Header + &lt;b&gt;&lt;i class=s&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&amp;gt; {
    &lt;b class=c&gt;&lt;i&gt;/// The name of the header that shall be used for retreiving and setting.&lt;/i&gt;&lt;/b&gt;
    &lt;b class=c&gt;&lt;i&gt;///&lt;/i&gt;&lt;/b&gt;
    &lt;b class=c&gt;&lt;i&gt;/// Normally this will be a static string, but occasionally it may be necessary to define it at&lt;/i&gt;&lt;/b&gt;
    &lt;b class=c&gt;&lt;i&gt;/// runtime, for dynamic header handling.&lt;/i&gt;&lt;/b&gt;
    &lt;b&gt;fn&lt;/b&gt; header_name(&lt;b&gt;&amp;amp;self&lt;/b&gt;) -&amp;gt; SendStr;
}

&lt;b class=c&gt;&lt;i&gt;/// The data type for the ``expires`` header.&lt;/i&gt;&lt;/b&gt;
&lt;i&gt;#[deriving(Clone, Eq, Show)]&lt;/i&gt;
&lt;b&gt;pub enum&lt;/b&gt; Expires {
    &lt;b class=c&gt;&lt;i&gt;/// The Expires header had an invalid format, which MUST be interpreted as “in the past”.&lt;/i&gt;&lt;/b&gt;
    Past,
    &lt;b class=c&gt;&lt;i&gt;/// A valid Expires header date.&lt;/i&gt;&lt;/b&gt;
    ExpiresDate(Tm),
}

&lt;b&gt;impl&lt;/b&gt; Header &lt;b&gt;for&lt;/b&gt; Expires {
    &lt;b&gt;fn&lt;/b&gt; parse_header(raw: &lt;b&gt;&amp;amp;&lt;/b&gt;[Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;]) -&amp;gt; Option&amp;lt;Expires&amp;gt; {
        &lt;i&gt;require_single_field!&lt;/i&gt;(raw);
        &lt;b&gt;match&lt;/b&gt; Header::parse_header(raw) {
            Some(tm) =&amp;gt; Some(ExpiresDate(tm)),
            None =&amp;gt; Some(Past),
        }
    }

    &lt;b&gt;fn&lt;/b&gt; fmt_header(&lt;b&gt;&amp;amp;self&lt;/b&gt;, f: &lt;b&gt;&amp;amp;mut&lt;/b&gt; fmt::Formatter) -&amp;gt; fmt::Result {
        &lt;b&gt;match *&lt;/b&gt;self {
            Past =&amp;gt; &lt;i&gt;write!&lt;/i&gt;(f.buf, &lt;span class=s&gt;&quot;0&quot;&lt;/span&gt;),
            ExpiresDate(&lt;b&gt;ref&lt;/b&gt; tm) =&amp;gt; tm.fmt_header(f),
        }
    }
}

&lt;b&gt;impl&lt;/b&gt; Header &lt;b&gt;for&lt;/b&gt; Tm {
    &lt;b&gt;fn&lt;/b&gt; parse_header(raw: &lt;b&gt;&amp;amp;&lt;/b&gt;[Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;]) -&amp;gt; Option&amp;lt;Tm&amp;gt; {
        &lt;b&gt;let&lt;/b&gt; raw = &lt;i&gt;require_single_field!&lt;/i&gt;(raw);
        &lt;b&gt;let&lt;/b&gt; raw = &lt;b&gt;match&lt;/b&gt; std::str::from_utf8(raw) {
            Some(raw) =&amp;gt; raw,
            None =&amp;gt; &lt;b&gt;return&lt;/b&gt; None,
        };
        &lt;i class=c&gt;// XXX: %Z actually ignores any timezone other than UTC. Probably not a good idea?&lt;/i&gt;
        &lt;b&gt;match&lt;/b&gt; strptime(raw, &lt;span class=s&gt;&quot;%a, %d %b %Y %T %Z&quot;&lt;/span&gt;) {  &lt;i class=c&gt;// RFC 822, updated by RFC 1123&lt;/i&gt;
            Ok(time) =&amp;gt; &lt;b&gt;return&lt;/b&gt; Some(time),
            Err(_) =&amp;gt; ()
        }

        &lt;b&gt;match&lt;/b&gt; strptime(raw, &lt;span class=s&gt;&quot;%A, %d-%b-%y %T %Z&quot;&lt;/span&gt;) {  &lt;i class=c&gt;// RFC 850, obsoleted by RFC 1036&lt;/i&gt;
            Ok(time) =&amp;gt; &lt;b&gt;return&lt;/b&gt; Some(time),
            Err(_) =&amp;gt; ()
        }

        &lt;b&gt;match&lt;/b&gt; strptime(raw, &lt;span class=s&gt;&quot;%c&quot;&lt;/span&gt;) {  &lt;i class=c&gt;// ANSI C&apos;s asctime() format&lt;/i&gt;
            Ok(time) =&amp;gt; Some(time),
            Err(_) =&amp;gt; None,
        }
    }

    &lt;b&gt;fn&lt;/b&gt; fmt_header(&lt;b&gt;&amp;amp;self&lt;/b&gt;, f: &lt;b&gt;&amp;amp;mut&lt;/b&gt; fmt::Formatter) -&amp;gt; fmt::Result {
        &lt;i&gt;write!&lt;/i&gt;(f.buf, &lt;span class=s&gt;&quot;&lt;b&gt;{}&lt;/b&gt;&quot;&lt;/span&gt;, self.to_utc().strftime(&lt;span class=s&gt;&quot;%a, %d %b %Y %T GMT&quot;&lt;/span&gt;))
    }
}

&lt;b&gt;impl&lt;/b&gt; Header &lt;b&gt;for Box&lt;/b&gt;&amp;lt;Header&amp;gt; {
    &lt;b&gt;fn&lt;/b&gt; parse_header(_raw: &lt;b&gt;&amp;amp;&lt;/b&gt;[Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;]) -&amp;gt; Option&amp;lt;Box&amp;lt;Header&amp;gt;&amp;gt; {
        &lt;i class=c&gt;// Dummy impl; XXX: split to ToHeader/FromHeader?&lt;/i&gt;
        None
    }

    &lt;b&gt;fn&lt;/b&gt; fmt_header(&lt;b&gt;&amp;amp;self&lt;/b&gt;, f: &lt;b&gt;&amp;amp;mut&lt;/b&gt; fmt::Formatter) -&amp;gt; fmt::Result {
        self.fmt_header(f)
    }
}

&lt;b&gt;impl&lt;/b&gt;&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt; Header &lt;b&gt;for&lt;/b&gt; &lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; Header {
    &lt;b&gt;fn&lt;/b&gt; parse_header(_raw: &lt;b&gt;&amp;amp;&lt;/b&gt;[Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;]) -&amp;gt; Option&amp;lt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; Header&amp;gt; {
        &lt;i class=c&gt;// Dummy impl; XXX: split to ToHeader/FromHeader?&lt;/i&gt;
        None
    }

    &lt;b&gt;fn&lt;/b&gt; fmt_header(&lt;b&gt;&amp;amp;self&lt;/b&gt;, f: &lt;b&gt;&amp;amp;mut&lt;/b&gt; fmt::Formatter) -&amp;gt; fmt::Result {
        self.fmt_header(f)
    }
}

&lt;i&gt;macro_rules!&lt;/i&gt; impl_header_from_fromstr {
    (&lt;span class=m&gt;$ty:ty&lt;/span&gt;) =&amp;gt; (&lt;b&gt;impl&lt;/b&gt; Header &lt;b&gt;for&lt;/b&gt; &lt;span class=m&gt;$ty&lt;/span&gt; {
        &lt;b&gt;fn&lt;/b&gt; parse_header(raw: &lt;b&gt;&amp;amp;&lt;/b&gt;[Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;]) -&amp;gt; Option&amp;lt;&lt;span class=m&gt;$ty&lt;/span&gt;&amp;gt; {
            std::str::from_utf8(raw).and_then(from_str)
        }

        &lt;b&gt;fn&lt;/b&gt; fmt_header(&lt;b&gt;&amp;amp;self&lt;/b&gt;, f: &lt;b&gt;&amp;amp;mut&lt;/b&gt; fmt::Formatter) -&amp;gt; fmt::Result {
            &lt;i&gt;write!&lt;/i&gt;(f.buf, &lt;span class=s&gt;&quot;&lt;b&gt;{}&lt;/b&gt;&quot;&lt;/span&gt;, self)
        }
    })
}

&lt;i&gt;macro_rules!&lt;/i&gt; header {
    (&lt;span class=m&gt;$struct_ident:ident&lt;/span&gt;, &lt;span class=m&gt;$header_name:expr&lt;/span&gt;, &lt;span class=m&gt;$output_type:ty&lt;/span&gt;) =&amp;gt; (
        &lt;b&gt;pub struct&lt;/b&gt; &lt;span class=m&gt;$struct_ident&lt;/span&gt;;

        &lt;b&gt;impl&lt;/b&gt; HeaderMarker&amp;lt;&lt;span class=m&gt;$output_type&lt;/span&gt;&amp;gt; for &lt;span class=m&gt;$struct_ident&lt;/span&gt; {
            &lt;b&gt;fn&lt;/b&gt; header_name(&lt;b&gt;&amp;amp;self&lt;/b&gt;) -&amp;gt; SendStr {
                Slice(&lt;span class=m&gt;$header_name&lt;/span&gt;)
            }
        }
    )
}

&lt;i&gt;header!&lt;/i&gt;(EXPIRES, &lt;span class=s&gt;&quot;expires&quot;&lt;/span&gt;, Expires)
&lt;i&gt;header!&lt;/i&gt;(DATE, &lt;span class=s&gt;&quot;date&quot;&lt;/span&gt;, Tm)

&lt;b&gt;pub struct&lt;/b&gt; RawHeaderMarker {
    &lt;b&gt;pub&lt;/b&gt; name: SendStr,
}

&lt;b class=c&gt;&lt;i&gt;/// This grants you access to raw header values:
///
/// ```rust
/// # headers = Headers::new();
/// headers.set(raw(&quot;expires&quot;), &quot;bar&quot;.as_bytes().iter().map(|&amp;amp;x| x).collect());
/// assert_eq!(headers.get(raw(&quot;expires&quot;)).to_slice(), bytes!(&quot;bar&quot;));
/// ```
///
/// That is, the header collection values are interpreted as `Vec&amp;lt;u8&amp;gt;`.
///
/// You should largely avoid doing this.&lt;/i&gt;&lt;/b&gt;
&lt;b&gt;pub fn&lt;/b&gt; raw&amp;lt;S: IntoMaybeOwned&amp;lt;&lt;b&gt;&lt;i class=s&gt;&apos;static&lt;/i&gt;&lt;/b&gt;&amp;gt;&amp;gt;(s: S) -&amp;gt; RawHeaderMarker {
    RawHeaderMarker {
        name: s.into_maybe_owned()
    }
}

&lt;b&gt;impl&lt;/b&gt; HeaderMarker&amp;lt;Vec&amp;lt;Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;&amp;gt;&amp;gt; &lt;b&gt;for&lt;/b&gt; RawHeaderMarker {
    &lt;b&gt;fn&lt;/b&gt; header_name(&lt;b&gt;&amp;amp;self&lt;/b&gt;) -&amp;gt; SendStr {
        self.name.clone()
    }
}

&lt;b&gt;impl&lt;/b&gt; Header &lt;b&gt;for&lt;/b&gt; Vec&amp;lt;Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;&amp;gt; {
    &lt;b&gt;fn&lt;/b&gt; parse_header(raw: &lt;b&gt;&amp;amp;&lt;/b&gt;[Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;]) -&amp;gt; Option&amp;lt;Vec&amp;lt;Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;&amp;gt;&amp;gt; {
        Some(raw.iter().map(|x| x.clone()).collect())
    }

    &lt;b&gt;fn&lt;/b&gt; fmt_header(&lt;b&gt;&amp;amp;self&lt;/b&gt;, f: &lt;b&gt;&amp;amp;mut&lt;/b&gt; fmt::Formatter) -&amp;gt; fmt::Result {
        &lt;b&gt;let mut&lt;/b&gt; first = true;
        &lt;b&gt;for&lt;/b&gt; field &lt;b&gt;in&lt;/b&gt; self.iter() {
            &lt;i&gt;try!&lt;/i&gt;(f.buf.write(field.as_slice()));
            &lt;b&gt;if&lt;/b&gt; !first {
                &lt;i&gt;try!&lt;/i&gt;(f.buf.write([&lt;span class=s&gt;&apos;,&apos;&lt;/span&gt; as u8, &lt;span class=s&gt;&apos; &apos;&lt;/span&gt; as u8]));
            }
            first = &lt;b&gt;false&lt;/b&gt;;
        }
        Ok(())
    }
}

&lt;b&gt;enum&lt;/b&gt; Item {
    &lt;b class=c&gt;&lt;i&gt;/// A raw, unparsed header. Uses the ISO-8859-1 character set, but could contain things in other&lt;/i&gt;&lt;/b&gt;
    &lt;b class=c&gt;&lt;i&gt;/// character sets according to the rules of RFC 2047, e.g. in a *TEXT rule (RFC 2616 grammar).&lt;/i&gt;&lt;/b&gt;
    Raw(Vec&amp;lt;Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;&amp;gt;),

    &lt;b class=c&gt;&lt;i&gt;/// A strongly typed header which has been parsed from the raw value.&lt;/i&gt;&lt;/b&gt;
    Typed(Box&amp;lt;Header&amp;gt;:&lt;b&gt;&lt;i class=s&gt;&apos;static&lt;/i&gt;&lt;/b&gt;),
}

&lt;b class=c&gt;&lt;i&gt;/// A collection of HTTP headers.&lt;/i&gt;&lt;/b&gt;
&lt;b&gt;struct&lt;/b&gt; Headers {
    data: HashMap&amp;lt;SendStr, Item&amp;gt;,
}

&lt;b&gt;impl&lt;/b&gt; Headers {
    &lt;b&gt;fn&lt;/b&gt; new() -&amp;gt; Headers {
        Headers {
            data: HashMap::new(),
        }
    }
}

&lt;i class=c&gt;/* I think I&apos;ll skip the Index implementation, though it works OK.
impl&amp;lt;H: Header + Clone + &apos;static, M: HeaderMarker&amp;lt;H&amp;gt;&amp;gt; Index&amp;lt;M, Option&amp;lt;H&amp;gt;&amp;gt; for Headers {
    fn index(&amp;amp;self, header_marker: &amp;amp;M) -&amp;gt; Option&amp;lt;H&amp;gt; {
        let mut_self = unsafe { std::cast::transmute_mut(self) };
        match mut_self.mostly_get(header_marker) {
            Some(&amp;amp;Typed(ref h)) =&amp;gt; Some(unsafe { h.as_ref_unchecked::&amp;lt;H&amp;gt;() }.clone()),
            _ =&amp;gt; None,
        }
    }
}
*/&lt;/i&gt;

&lt;b&gt;impl&lt;/b&gt;&amp;lt;H: Header + Clone + &lt;b&gt;&lt;i class=s&gt;&apos;static&lt;/i&gt;&lt;/b&gt;, M: HeaderMarker&amp;lt;H&amp;gt;&amp;gt; Headers {
    &lt;b&gt;pub fn&lt;/b&gt; get&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt;(&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; &lt;b&gt;mut self&lt;/b&gt;, header_marker: M) -&amp;gt; Option&amp;lt;H&amp;gt; {
        &lt;i class=c&gt;// At this point, we know that item is None, or Some(&amp;amp;mut Typed(h)) and that h.is::&amp;lt;H&amp;gt;().&lt;/i&gt;
        &lt;i class=c&gt;// On that basis, we can use as_ref_unchecked instead of as_ref, to save a virtual call.&lt;/i&gt;
        &lt;b&gt;match&lt;/b&gt; self.mostly_get(&lt;b&gt;&amp;amp;&lt;/b&gt;header_marker) {
            Some(&lt;b&gt;&amp;amp;&lt;/b&gt;Typed(ref h)) =&amp;gt; Some(&lt;b&gt;unsafe&lt;/b&gt; { h.as_ref_unchecked::&amp;lt;H&amp;gt;() }.clone()),
            _ =&amp;gt; None,
        }
    }
}

&lt;b&gt;impl&lt;/b&gt;&amp;lt;H: Header + &lt;b&gt;&lt;i class=s&gt;&apos;static&lt;/i&gt;&lt;/b&gt;, M: HeaderMarker&amp;lt;H&amp;gt;&amp;gt; Headers {
    &lt;b&gt;fn&lt;/b&gt; mostly_get&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt;(&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; &lt;b&gt;mut self&lt;/b&gt;, header_marker: &lt;b&gt;&amp;amp;&lt;/b&gt;M) -&amp;gt; Option&amp;lt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; &lt;b&gt;mut&lt;/b&gt; Item&amp;gt; {
        &lt;b&gt;let&lt;/b&gt; name = header_marker.header_name();
        &lt;b&gt;let&lt;/b&gt; item = &lt;b&gt;match&lt;/b&gt; self.data.find_mut(&lt;b&gt;&amp;amp;&lt;/b&gt;name) {
            &lt;i class=c&gt;// Yes, there&apos;s a header… or something… by that name&lt;/i&gt;
            Some(v) =&amp;gt; v,
            &lt;i class=c&gt;// Header? There is no header!&lt;/i&gt;
            None =&amp;gt; &lt;b&gt;return&lt;/b&gt; None,
        };

        &lt;b&gt;let&lt;/b&gt; (insert_parsed, parsed): (&lt;b&gt;bool&lt;/b&gt;, Option&amp;lt;H&amp;gt;) = &lt;b&gt;match&lt;/b&gt; *item {
            &lt;i class=c&gt;// We&apos;ve parsed this header before, as some type or other.&lt;/i&gt;
            &lt;i class=c&gt;// Question is: is it the right type?&lt;/i&gt;

            &lt;i class=c&gt;// Yes, it&apos;s the right type, so we can immediately return it.&lt;/i&gt;
            &lt;i class=c&gt;// Well, we could, except that that makes the borrow checker keep the item borrow alive,&lt;/i&gt;
            &lt;i class=c&gt;// preventing the insert in the other cases. So we must refactor it to return at the&lt;/i&gt;
            &lt;i class=c&gt;// end instead.&lt;/i&gt;
            Typed(&lt;b&gt;ref&lt;/b&gt; h) &lt;b&gt;if&lt;/b&gt; h.is::&amp;lt;H&amp;gt;() =&amp;gt; {
                (&lt;b&gt;false&lt;/b&gt;, None)
            },

            &lt;i class=c&gt;// No, it was parsed as a different type.&lt;/i&gt;
            &lt;i class=c&gt;// Very well then, we will turn it back into a string first.&lt;/i&gt;
            Typed(&lt;b&gt;ref&lt;/b&gt; h) =&amp;gt; {
                &lt;b&gt;let&lt;/b&gt; raw = fmt_header(h);
                (&lt;b&gt;true&lt;/b&gt;, Header::parse_header([raw]))
            },

            &lt;i class=c&gt;// We haven&apos;t parsed it before, so let&apos;s have a go at that.&lt;/i&gt;
            Raw(&lt;b&gt;ref&lt;/b&gt; raw) =&amp;gt; (&lt;b&gt;true&lt;/b&gt;, Header::parse_header(raw.as_slice())),
        };

        &lt;b&gt;if&lt;/b&gt; insert_parsed {
            &lt;b&gt;match&lt;/b&gt; parsed {
                &lt;i class=c&gt;// It parsed. Let&apos;s store the new value (replacing the raw one)&lt;/i&gt;
                Some(v) =&amp;gt; &lt;b&gt;*&lt;/b&gt;item = Typed(&lt;b&gt;box&lt;/b&gt; v),
                &lt;i class=c&gt;// If the header doesn&apos;t parse, that&apos;s the same as it being absent.&lt;/i&gt;
                None =&amp;gt; &lt;b&gt;return&lt;/b&gt; None,
            }
        }
        Some(item)
    }

    &lt;b&gt;pub fn&lt;/b&gt; get_ref&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt;(&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; &lt;b&gt;mut self&lt;/b&gt;, header_marker: M) -&amp;gt; Option&amp;lt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; H&amp;gt; {
        &lt;b&gt;match&lt;/b&gt; self.mostly_get(&lt;b&gt;&amp;amp;&lt;/b&gt;header_marker) {
            Some(&lt;b&gt;&amp;amp;&lt;/b&gt;Typed(&lt;b&gt;ref&lt;/b&gt; h)) =&amp;gt; Some(&lt;b&gt;unsafe&lt;/b&gt; { h.as_ref_unchecked::&amp;lt;H&amp;gt;() }),
            _ =&amp;gt; None,
        }
    }

    &lt;b&gt;pub fn&lt;/b&gt; get_mut_ref&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;&amp;gt;(&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; &lt;b&gt;mut self&lt;/b&gt;, header_marker: M) -&amp;gt; Option&amp;lt;&lt;b&gt;&amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; &lt;b&gt;mut&lt;/b&gt; H&amp;gt; {
        &lt;b&gt;match&lt;/b&gt; self.mostly_get(&lt;b&gt;&amp;amp;&lt;/b&gt;header_marker) {
            Some(&lt;b&gt;&amp;amp;&lt;/b&gt;Typed(&lt;b&gt;ref mut&lt;/b&gt; h)) =&amp;gt; Some(&lt;b&gt;unsafe&lt;/b&gt; { h.as_mut_unchecked::&amp;lt;H&amp;gt;() }),
            _ =&amp;gt; None,
        }
    }

    &lt;b class=c&gt;&lt;i&gt;/// Set the named header to the given value.&lt;/i&gt;&lt;/b&gt;
    &lt;b&gt;pub fn&lt;/b&gt; set(&lt;b&gt;&amp;amp;mut self&lt;/b&gt;, header_marker: M, value: H) {
        self.data.insert(header_marker.header_name(), Typed(&lt;b&gt;box&lt;/b&gt; value));
    }

    &lt;b class=c&gt;&lt;i&gt;/// Remove a header from the collection.&lt;/i&gt;&lt;/b&gt;
    &lt;b class=c&gt;&lt;i&gt;/// Returns true if the named header was present.&lt;/i&gt;&lt;/b&gt;
    &lt;b&gt;pub fn&lt;/b&gt; remove(&lt;b&gt;&amp;amp;mut self&lt;/b&gt;, header_marker: &lt;b&gt;&amp;amp;&lt;/b&gt;M) {
        self.data.remove(&lt;b&gt;&amp;amp;&lt;/b&gt;header_marker.header_name());
    }
}

&lt;b class=c&gt;&lt;i&gt;/// An adapter which provides `std::fmt::Show` as equivalent to `Header.fmt_header`, so that you can
/// actually *use* the thing.&lt;/i&gt;&lt;/b&gt;
&lt;b&gt;struct&lt;/b&gt; HeaderShowAdapter&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;, H&amp;gt;(&lt;b&gt;pub &amp;amp;&lt;/b&gt;&lt;i class=s&gt;&apos;a&lt;/i&gt; H);

&lt;b&gt;impl&lt;/b&gt;&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;, H: Header&amp;gt; fmt::Show &lt;b&gt;for&lt;/b&gt; HeaderShowAdapter&amp;lt;&lt;i class=s&gt;&apos;a&lt;/i&gt;, H&amp;gt; {
    &lt;i&gt;#[inline]&lt;/i&gt;
    &lt;b&gt;fn&lt;/b&gt; fmt(&lt;b&gt;&amp;amp;self&lt;/b&gt;, f: &lt;b&gt;&amp;amp;mut&lt;/b&gt; fmt::Formatter) -&amp;gt; fmt::Result {
        &lt;b&gt;let&lt;/b&gt; HeaderShowAdapter(h) = *self;
        h.fmt_header(f)
    }
}

&lt;i&gt;#[inline]&lt;/i&gt;
&lt;b&gt;pub fn&lt;/b&gt; fmt_header&amp;lt;H: Header&amp;gt;(h: &lt;b&gt;&amp;amp;&lt;/b&gt;H) -&amp;gt; Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt; {
    &lt;i&gt;format_args!&lt;/i&gt;(format_but_not_utf8, &lt;span class=s&gt;&quot;&lt;b&gt;{}&lt;/b&gt;&quot;&lt;/span&gt;, HeaderShowAdapter(h))
}

&lt;i class=c&gt;// Parallel to ::std::fmt::{format, format_unsafe}, but returning Vec&amp;lt;u8&amp;gt; rather than Box&amp;lt;str&amp;gt;.&lt;/i&gt;
&lt;i&gt;#[inline]&lt;/i&gt;
&lt;i&gt;#[doc(hidden)]&lt;/i&gt;
&lt;b&gt;pub fn&lt;/b&gt; format_but_not_utf8(args: &lt;b&gt;&amp;amp;&lt;/b&gt;fmt::Arguments) -&amp;gt; Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt; {
    &lt;b&gt;let mut&lt;/b&gt; output = std::io::MemWriter::new();
    fmt::write(&lt;b&gt;&amp;amp;mut&lt;/b&gt; output as &lt;b&gt;&amp;amp;mut&lt;/b&gt; Writer, args).unwrap();
    output.unwrap()
}

&lt;b&gt;fn&lt;/b&gt; main() {
    &lt;b&gt;let mut&lt;/b&gt; headers = Headers::new();
    &lt;b&gt;fn&lt;/b&gt; expect&amp;lt;H: Header + std::fmt::Show + Eq&amp;gt;(h: Option&amp;lt;H&amp;gt;, h_expected: H, raw: &lt;b&gt;&amp;amp;&lt;/b&gt;[u8]) {
        &lt;b&gt;let&lt;/b&gt; h = h.unwrap();
        &lt;i&gt;assert_eq!&lt;/i&gt;(fmt_header(&lt;b&gt;&amp;amp;&lt;/b&gt;h).as_slice(), raw);
        &lt;i&gt;assert_eq!&lt;/i&gt;(h, h_expected);
    }
    &lt;b&gt;fn&lt;/b&gt; expect_none&amp;lt;H: Header&amp;gt;(h: Option&amp;lt;H&amp;gt;) {
        &lt;i&gt;assert!&lt;/i&gt;(h.is_none());
    }

    expect_none(headers.get(EXPIRES));
    headers.set(EXPIRES, Past);
    expect(headers.get(EXPIRES), Past, &lt;i&gt;bytes!&lt;/i&gt;(&lt;span class=s&gt;&quot;0&quot;&lt;/span&gt;));
    expect(headers.get(raw(&lt;span class=s&gt;&quot;expires&quot;&lt;/span&gt;)), &lt;i&gt;vec!&lt;/i&gt;(&lt;i&gt;vec!&lt;/i&gt;(&apos;0&apos; as u8)), &lt;i&gt;bytes!&lt;/i&gt;(&lt;span class=s&gt;&quot;0&quot;&lt;/span&gt;));
    expect(headers.get(EXPIRES), Past, &lt;i&gt;bytes!&lt;/i&gt;(&lt;span class=s&gt;&quot;0&quot;&lt;/span&gt;));
    headers.remove(&lt;b&gt;&amp;amp;&lt;/b&gt;EXPIRES);
    expect_none(headers.get(EXPIRES));

    expect_none(headers.get(DATE));
    &lt;b&gt;let&lt;/b&gt; now = time::now();
    &lt;b&gt;let&lt;/b&gt; now_raw = fmt_header(&lt;b&gt;&amp;amp;&lt;/b&gt;now);
    headers.set(DATE, now.clone());
    expect(headers.get(DATE), now.clone(), now_raw.as_slice());
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;h2&gt;Assessment&lt;/h2&gt;
&lt;p&gt;Here’s how this goes on the criteria listed:
&lt;ol&gt;
    &lt;li&gt;&lt;p&gt;&lt;strong&gt;Performance must be “good”.&lt;/strong&gt;&lt;br&gt; The good news: headers are parsed lazily. The bad news: two or three allocations per header field, plus an allocation and a deallocation for every type change (including that lazy parsing). Performance is, I think, the weakest part of this scheme, but I don’t believe anything faster is possible while still ticking all the other boxes.
    &lt;li&gt;&lt;p&gt;&lt;strong&gt;Ergonomics for using standardised headers must be “good”.&lt;/strong&gt;&lt;br&gt; There’s a certain perfection about field access… but this will do dandy.
    &lt;li&gt;&lt;p&gt;&lt;strong&gt;Ergonomics for using extension headers must be “good”.&lt;/strong&gt;&lt;br&gt; As above.
    &lt;li&gt;&lt;p&gt;&lt;strong&gt;Extension headers should be strongly typed.&lt;/strong&gt;&lt;br&gt; Got it.
    &lt;li&gt;&lt;p&gt;&lt;strong&gt;Badly formatted headers must be accessible in &lt;em&gt;some&lt;/em&gt; way.&lt;/strong&gt;&lt;br&gt; Readily accessible, though accessing a header as a strongly typed value will destroy the raw stuff, so anyone caring about such things &lt;em&gt;will&lt;/em&gt; need to be careful.
    &lt;li&gt;&lt;p&gt;&lt;strong&gt;A shared access technique for both standardised and extension headers is desirable (for backwards compatibility as more headers are added to the Teepee libraries), especially if it allows headers to be used as multiple types.&lt;/strong&gt;&lt;br&gt; This solution absolutely shines at this: if two libraries want to access the same header as a different type, it will happily convert between them, just sacrificing a little bit of performance for the benefit.
&lt;/ol&gt;
&lt;p&gt;Unless anyone finds any significant problems with this scheme, or a better scheme, Teepee will be using this type of header collection.
&lt;h3&gt;Remaining questions&lt;/h3&gt;
&lt;ol&gt;
    &lt;li&gt;&lt;p&gt;Should access to the raw values be granted via unsafe functions, or should typed access be genuinely the only interface exposed, leaving an implementation for &lt;code&gt;Vec&amp;lt;Vec&amp;lt;&lt;b&gt;u8&lt;/b&gt;&amp;gt;&amp;gt;&lt;/code&gt; as the way of accessing raw values? (Side note: without that, the library will accept multiple header fields with the same name, but will merge them separated by a comma when writing them. This is perfectly spec‐compliant behaviour, but it is conceivable that someone may wish to genuinely write multiple header fields with the same name and &lt;em&gt;not&lt;/em&gt; merge them. I guess I probably just talked myself into answering this question. Still, without such behaviour, the header collections for &lt;em&gt;writing&lt;/em&gt; could skip the possibility of a raw value and just use a &lt;code&gt;Box&amp;lt;Header&amp;gt;&lt;/code&gt; directly instead of &lt;code&gt;Item&lt;/code&gt;, which would produce moderately trivial performance improvements. So I guess the quesiton &lt;em&gt;is&lt;/em&gt; still open. Can anyone think of a way that one could use the &lt;code&gt;std::fmt&lt;/code&gt; interface and yet still allow the writing of multiple header fields from the one value?)

    &lt;li&gt;&lt;p&gt;Is jumping on the tails of &lt;code&gt;std::fmt&lt;/code&gt; a good idea? (Bear in mind that &lt;code&gt;std::fmt&lt;/code&gt; is UTF-8‐centric while HTTP is ISO-8859-1‐centric, though I do not really know if that influences thing.)

    &lt;li&gt;&lt;p&gt;At present, the header collections for requests and responses have different fields; should the header markers use phantom types to specify that they are only legal for requests or responses (or both)? That would make it so that &lt;code&gt;request.headers.set(REFERER, …)&lt;/code&gt; would work while &lt;code&gt;response.headers.set(REFERER, …)&lt;/code&gt; would fail to compile.
&lt;/ol&gt;
&lt;p&gt;I now invite you to &lt;a href=https://www.reddit.com/r/rust/comments/254q2o/teepee_design_header_representation/&gt;join in the discussion at /r/rust&lt;/a&gt;.

			&lt;aside class=trailer&gt;
		&lt;hr&gt;
		&lt;p&gt;Comments? Questions? Corrections? If you want to contact me about anything in this post, email me at &lt;a href=&quot;mailto:me@chrismorgan.info&quot;&gt;me@chrismorgan.info&lt;/a&gt;.
	&lt;/aside&gt;
		</content>
	</entry>
	<entry xml:base="https://chrismorgan.info/blog/teepee-design-status-line-take-two/">
		<title type="html">Teepee design: &lt;code&gt;Status-Line&lt;/code&gt;, take two</title>
		<published>2014-04-25T00:00:00+00:00</published>
		<updated>2014-04-25T00:00:00+00:00</updated>
		<link href="https://chrismorgan.info/blog/teepee-design-status-line-take-two/" type="text/html"/>
		<id>http://chrismorgan.info/blog/teepee-design-status-line-take-two.html</id>
		<category scheme="https://chrismorgan.info/blog/tags/" term="web" label="Web" />
		<category scheme="https://chrismorgan.info/blog/tags/" term="rust" label="Rust" />
		<category scheme="https://chrismorgan.info/blog/tags/" term="teepee" label="Teepee" />
		<content type="html">
			&lt;p class=intro&gt;&lt;a href=/blog/teepee-design-status-line/&gt;My first look at the &lt;code&gt;Status-Line&lt;/code&gt;&lt;/a&gt; kept largely to what rust-http had done; &lt;a href=https://www.reddit.com/r/rust/comments/23vbbt/teepee_design_a_careful_look_at_the_http11/&gt;some great discussion came up&lt;/a&gt; and a conceptual flaw in my models was revealed. Now I present some better options.
			&lt;p&gt;&lt;em&gt;This article is part of the series on &lt;a href=/blog/introducing-teepee/&gt;the rust-http redesign, Teepee&lt;/a&gt;.&lt;/em&gt;
&lt;p&gt;Of the first article, most details are superseded here; the most important part that is still definitely in place is the &lt;a href=/blog/teepee-design-status-line/#class&gt;status code class&lt;/a&gt; part.
&lt;h2&gt;The criticism and responses to it&lt;/h2&gt;
&lt;p&gt;The main point of criticism levelled at the designs I posted is that it was still treating the &lt;code&gt;Reason-Phrase&lt;/code&gt; too importantly.
&lt;p&gt;Some argue in favour of dropping the reason phrase altogether. That I am not willing to do, citing the &lt;a href=/blog/teepee-design-status-line/#451&gt;451 example&lt;/a&gt; for justification. No, the reason phrase must remain around, somewhere.
&lt;p&gt;A common suggestion is splitting the status code and reason phrase apart. This is looking like a healthy option. It is one that had not occurred to me; I had become too tied up in their correlation, that being what I had been working with in the past in rust-http.
&lt;p&gt;Library designers, beware—​your own perspective will become warped over time so that you often see only slight variations from what you are doing. Getting fresh eyes on a solution is &lt;em&gt;marvellous&lt;/em&gt;; I am very glad that I wrote about this matter. Thank you, everyone, for the feedback: Teepee will be the stronger for it.
&lt;h2&gt;The new design&lt;/h2&gt;
&lt;p&gt;I now present a new design, influenced strongly by the feedback received.
&lt;p&gt;At the lowest level, rather than giving a single &lt;code&gt;Status&lt;/code&gt; object, the code will work with the pair &lt;code&gt;(StatusCode, ReasonPhrase)&lt;/code&gt;.
&lt;p&gt;Responses received by the client will have both of these:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;struct&lt;/b&gt; Response {
    status_code: StatusCode,
    reason_phrase: &lt;b&gt;~str&lt;/b&gt;,
    ...
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;Responses a server is writing will have both fields, but with the reason phrase optional:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;struct&lt;/b&gt; Response {
    status_code: StatusCode,
    reason_phrase: Option&amp;lt;&lt;b&gt;~str&lt;/b&gt;&amp;gt;,
    ...
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;Normally people will just set the status code. If the reason phrase is &lt;code&gt;None&lt;/code&gt;, the appropriate value will be inferred, or for unknown statuses, something like “&amp;lt;no reason phrase given&amp;gt;”.
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;impl&lt;/b&gt; StatusCode {
    &lt;b&gt;fn&lt;/b&gt; default_reason(&lt;b&gt;&amp;amp;self&lt;/b&gt;) -&amp;gt; Option&amp;lt;&lt;b&gt;&amp;amp;&lt;i class=s&gt;&apos;static&lt;/i&gt; str&lt;/b&gt;&amp;gt; {
        &lt;b&gt;match&lt;/b&gt; self.to_u16() {
            &lt;span class=n&gt;100&lt;/span&gt; =&amp;gt; Some(&lt;span class=s&gt;&quot;Continue&quot;&lt;/span&gt;),
            &lt;span class=n&gt;101&lt;/span&gt; =&amp;gt; Some(&lt;span class=s&gt;&quot;Switching Protocols&quot;&lt;/span&gt;),
            &lt;span class=n&gt;102&lt;/span&gt; =&amp;gt; Some(&lt;span class=s&gt;&quot;Processing&quot;&lt;/span&gt;),
            &lt;span class=n&gt;200&lt;/span&gt; =&amp;gt; Some(&lt;span class=s&gt;&quot;OK&quot;&lt;/span&gt;),
            ...,
            _ =&amp;gt; None,
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;I am satisfied with this design. Now the only question remaining is how &lt;code&gt;StatusCode&lt;/code&gt; itself is represented.
&lt;h2&gt;The &lt;code&gt;StatusCode&lt;/code&gt; part: a few designs&lt;/h2&gt;
&lt;p&gt;There are a few possibilities for the Status-Code part; I present here a few, each with its benefits and drawbacks. Their ordering is not significant.
&lt;h3&gt;#1: an enum with an extension code variant&lt;/h3&gt;
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;pub&lt;/b&gt; &lt;b&gt;enum&lt;/b&gt; StatusCode {
    Continue,
    SwitchingProtocols,
    Ok,
    ...,
    ExtensionCode(&lt;b&gt;u16&lt;/b&gt;),
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;This is similar to what is done in rust-http. It takes four bytes, while the others take two bytes. 
&lt;p&gt;This maps extremely well onto the &lt;a href=https://tools.ietf.org/html/rfc2616#section-6.1.1&gt;RFC 2616 definition of &lt;code&gt;Status-Code&lt;/code&gt;&lt;/a&gt;:
&lt;figure&gt;&lt;blockquote&gt;&lt;pre&gt;      Status-Code    =
            &quot;100&quot;  ; Section 10.1.1: Continue
          | &quot;101&quot;  ; Section 10.1.2: Switching Protocols
          | &quot;200&quot;  ; Section 10.2.1: OK
&lt;em&gt;[many fields omitted for brevity]&lt;/em&gt;
          | extension-code

      extension-code = 3DIGIT&lt;/pre&gt;&lt;/blockquote&gt;&lt;/figure&gt;
&lt;p&gt;However, this has the backwards‐compatibility problem (one I identified earlier but forgot to write down in my previous article) that when a new status &lt;code class=status-code&gt;103 Newly Registered Value&lt;/code&gt; is registered, things will change from using &lt;code&gt;ExtensionCode(&lt;span class=n&gt;103&lt;/span&gt;)&lt;/code&gt; to using &lt;code&gt;NewlyRegisteredValue&lt;/code&gt;. It’s a very rare case, but very significant.
&lt;h3&gt;#2: a 500‐variant C‐style enum&lt;/h3&gt;
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;pub&lt;/b&gt; &lt;b&gt;enum&lt;/b&gt; StatusCode {
    Continue = &lt;span class=n&gt;100&lt;/span&gt;,
    SwitchingProtocols = &lt;span class=n&gt;101&lt;/span&gt;,
    Processing = &lt;span class=n&gt;102&lt;/span&gt;,
    Code103 = &lt;span class=n&gt;103&lt;/span&gt;,
    Code104 = &lt;span class=n&gt;104&lt;/span&gt;,
    ...,
    Ok = &lt;span class=n&gt;200&lt;/span&gt;,
    ...,
    Code599 = &lt;span class=n&gt;599&lt;/span&gt;,
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;This scheme has the slight weakness that when a status becomes registered, its variant will change; this is not, however, a severe backwards‐compatibility problem, for we would leave static aliases behind (e.g. &lt;code&gt;pub static Code103: StatusCode = NewlyRegisteredValue&lt;/code&gt;). That could also be used to take care of cases like 451.
&lt;aside&gt;
	&lt;h3&gt;Aside: performance trivia&lt;/h3&gt;
    &lt;p&gt;Alas, rustc’s &lt;code&gt;&lt;i&gt;#[deriving]&lt;/i&gt;&lt;/code&gt; codegen doesn’t do too well for such a large C‐style enum.
    &lt;p&gt;On my machine, &lt;code&gt;&lt;i&gt;#[deriving(Eq)]&lt;/i&gt;&lt;/code&gt; adds 1.2 seconds to compile time, because it produces a needlessly complex implementation that compares every alternative, rather than just &lt;code&gt;&lt;b&gt;*&lt;/b&gt;self &lt;b&gt;as u16&lt;/b&gt; == &lt;b&gt;*&lt;/b&gt;other &lt;b&gt;as u16&lt;/b&gt;&lt;/code&gt;. Sure, the optimiser optimises it all out, but such a degree of slowness is surprising.
    &lt;p&gt;&lt;code&gt;&lt;i&gt;#[deriving(Clone)]&lt;/i&gt;&lt;/code&gt; similarly does &lt;code&gt;&lt;b&gt;match *&lt;/b&gt;self { Code100 =&amp;gt; Code100, ... }&lt;/code&gt; and adds 0.4 seconds to compile time. That also can be cut down to just &lt;code&gt;&lt;b&gt;*&lt;/b&gt;self&lt;/code&gt;.
    &lt;p&gt;Apart from these compile time problems, performance is no problem. I guess I’d just go for manually implementing them to save 1.6 seconds of compile time.
&lt;/aside&gt;
&lt;h3&gt;#3: a simple wrapping struct with associated statics&lt;/h3&gt;
&lt;p&gt;I handle this as a separate struct rather than just as &lt;code&gt;&lt;b&gt;u16&lt;/b&gt;&lt;/code&gt;, because there are only 500 valid values (100–599). Just as &lt;code&gt;&lt;b&gt;~str&lt;/b&gt;&lt;/code&gt; applies checks to maintain the invariant that it is valid UTF-8, I will ensure that an illegal &lt;code&gt;StatusCode&lt;/code&gt; can never exist. (That applies to the &lt;code&gt;ExtensionCode&lt;/code&gt; variant of the enum solution too, by the way.)
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;pub&lt;/b&gt; &lt;b&gt;struct&lt;/b&gt; StatusCode {
    code: &lt;b&gt;u16&lt;/b&gt;,
}

&lt;i class=c&gt;// 1xx Informational&lt;/i&gt;
&lt;b&gt;pub&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; CONTINUE: Status = Status { code: &lt;span class=n&gt;100&lt;/span&gt; };
&lt;b&gt;pub&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; SWITCHING_PROTOCOLS: Status = Status { code: &lt;span class=n&gt;101&lt;/span&gt; };
&lt;b&gt;pub&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; PROCESSING: Status = Status { code: &lt;span class=n&gt;101&lt;/span&gt; };

&lt;i class=c&gt;// 2xx Success&lt;/i&gt;
&lt;b&gt;pub&lt;/b&gt; &lt;b&gt;static&lt;/b&gt; OK: Status = Status { code: &lt;span class=n&gt;200&lt;/span&gt; };
...
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;The biggest thing this has going against it is that pattern matching won’t work.
&lt;h3&gt;#4: just a number&lt;/h3&gt;
&lt;p&gt;A variant of #3, one can cause pattern matching to work by using a number type directly:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;pub&lt;/b&gt; &lt;b&gt;type&lt;/b&gt; StatusCode = &lt;b&gt;u16&lt;/b&gt;;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;I am not in favour of this solution because of semantic mismatch. A status is &lt;em&gt;not&lt;/em&gt; just a number—​it has 500 valid values, as mentioned above, and I wish to maintain the invariant. Also things like &lt;code&gt;+&lt;/code&gt; simply don’t make sense for a status. Sure, it’s &lt;em&gt;shown&lt;/em&gt; as a number, but it is opaque data.
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;I am now satisfied with the overall design of the &lt;code&gt;Status-Line&lt;/code&gt; handling. As to the representation of &lt;code&gt;StatusCode&lt;/code&gt;, my current order of preferences, from favourite to least favourite, is #2, #3, #1, #4.
&lt;p&gt;I now invite you to &lt;a href=https://www.reddit.com/r/rust/comments/23xcaa/teepee_design_status_line_take_two/&gt;join in the discussion at /r/rust&lt;/a&gt;.
&lt;h2 id=http2&gt;Update: the HTTP/2.0 situation&lt;/h2&gt;
&lt;p&gt;Something I neglected to do all along was refer to &lt;a href=https://tools.ietf.org/html/draft-ietf-httpbis-http2-12&gt;the HTTP/2.0 specification&lt;/a&gt;. (I looked at that part a few months ago, but had forgotten about it. I’ve been focusing more on the multiplexing aspects of HTTP/2.0, as that’s the main change and the main area of implementation difficulty for Teepee.) It has a couple of notable changes:
&lt;ul&gt;
	&lt;li&gt;&lt;p&gt;The reason phrase is gone altogether (&lt;a href=https://tools.ietf.org/html/draft-ietf-httpbis-http2-12#section-8.1.3.2&gt;Section 8.1.3.2, Response Header Fields&lt;/a&gt;). This confirms that separating the code and the reason is the correct thing to do.

	&lt;li&gt;&lt;p&gt;1xx Informational class statuses are removed (&lt;a href=https://tools.ietf.org/html/draft-ietf-httpbis-http2-12#section-8.1.1&gt;Section 8.1.1, Informational Responses&lt;/a&gt;). This suggests that restricting the values structurally in the type system might not be quite so valuable, as only a subset of those values are actually valid in certain situations.
&lt;/ul&gt;

			&lt;aside class=trailer&gt;
		&lt;hr&gt;
		&lt;p&gt;Comments? Questions? Corrections? If you want to contact me about anything in this post, email me at &lt;a href=&quot;mailto:me@chrismorgan.info&quot;&gt;me@chrismorgan.info&lt;/a&gt;.
	&lt;/aside&gt;
		</content>
	</entry>
	<entry xml:base="https://chrismorgan.info/blog/teepee-design-status-line/">
		<title type="html">Teepee design: a careful look at the HTTP/1.1 &lt;code&gt;Status-Line&lt;/code&gt;</title>
		<published>2014-04-25T00:00:00+00:00</published>
		<updated>2014-04-25T00:00:00+00:00</updated>
		<link href="https://chrismorgan.info/blog/teepee-design-status-line/" type="text/html"/>
		<id>http://chrismorgan.info/blog/teepee-design-status-line.html</id>
		<category scheme="https://chrismorgan.info/blog/tags/" term="web" label="Web" />
		<category scheme="https://chrismorgan.info/blog/tags/" term="rust" label="Rust" />
		<category scheme="https://chrismorgan.info/blog/tags/" term="teepee" label="Teepee" />
		<content type="html">
			&lt;p class=intro&gt;rust-http has a nice &lt;code&gt;Status&lt;/code&gt; enum which provides good, strong typing of statuses, but alas, it is not without its issues. Let’s take a look at the &lt;code&gt;Status-Line&lt;/code&gt; as it is defined.
			&lt;p&gt;&lt;em&gt;This article is part of the series on &lt;a href=/blog/introducing-teepee/&gt;the rust-http redesign, Teepee&lt;/a&gt;.&lt;/em&gt;
&lt;aside class=alert&gt;
	&lt;p&gt;After &lt;a href=https://www.reddit.com/r/rust/comments/23vbbt/teepee_design_a_careful_look_at_the_http11/&gt;some great discussion&lt;/a&gt;, the direction I’m planning on taking Teepee has changed. Quite a bit of this article is superseded by &lt;a href=/blog/teepee-design-status-line-take-two/&gt;take two&lt;/a&gt;, though this article is still of value.
&lt;/aside&gt;
&lt;p&gt;I say &lt;code&gt;Status-Line&lt;/code&gt;, but actually I don’t care about part of it; &lt;a href=https://tools.ietf.org/html/rfc2616#section-6.1&gt;&lt;code&gt;Status-Line&lt;/code&gt; is defined in RFC 2616 (HTTP/1.1)&lt;/a&gt; as &lt;code&gt;HTTP-Version SP Status-Code SP Reason-Phrase CRLF&lt;/code&gt;, but all I care about in this article is the &lt;code&gt;Status-Code&lt;/code&gt; (e.g. &lt;code&gt;200&lt;/code&gt;) and its corresponding &lt;code&gt;Reason-Phrase&lt;/code&gt; (e.g. &lt;code&gt;OK&lt;/code&gt;).
&lt;h2&gt;The current position&lt;/h2&gt;
&lt;p&gt;At present, rust-http has &lt;code&gt;http::status::Status&lt;/code&gt;. Here’s the implementation, distilled:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;i&gt;#[deriving(Eq, Clone)]&lt;/i&gt;
&lt;b&gt;pub enum&lt;/b&gt; Status {
    &lt;i class=c&gt;// 1xx Informational&lt;/i&gt;
    Continue,
    SwitchingProtocols,
    Processing,  &lt;i class=c&gt;// WebDAV; RFC 2518&lt;/i&gt;

    &lt;i class=c&gt;// 2xx Success&lt;/i&gt;
    Ok,
    Created,
    ...,

    &lt;i class=c&gt;// 3xx Redirection&lt;/i&gt;
    MultipleChoices,
    MovedPermanently,
    ...,

    &lt;i class=c&gt;// 4xx Client Error&lt;/i&gt;
    BadRequest,
    Unauthorized,
    ...,

    &lt;i class=c&gt;// 5xx Server Error&lt;/i&gt;
    InternalServerError,
    NotImplemented,
    ...,

    UnregisteredStatus(&lt;b&gt;u16&lt;/b&gt;, &lt;b&gt;~str&lt;/b&gt;),
}

&lt;b&gt;impl&lt;/b&gt; Status {
    &lt;b class=c&gt;&lt;i&gt;/// Get the status code&lt;/i&gt;&lt;/b&gt;
    &lt;b&gt;pub fn&lt;/b&gt; code(&lt;b&gt;&amp;amp;self&lt;/b&gt;) -&amp;gt; &lt;b&gt;u16&lt;/b&gt; {
        &lt;b&gt;match *&lt;/b&gt;self {
            Continue =&amp;gt; &lt;span class=n&gt;100&lt;/span&gt;,
            ...,

            UnregisteredStatus(code, _)   =&amp;gt; code,
        }
    }

    &lt;b class=c&gt;&lt;i&gt;/// Get the reason phrase&lt;/i&gt;&lt;/b&gt;
    &lt;b&gt;pub fn&lt;/b&gt; reason(&lt;b&gt;&amp;amp;self&lt;/b&gt;) -&amp;gt; StrBuf {
        &lt;b&gt;match *&lt;/b&gt;self {
            Continue =&amp;gt; StrBuf::from_str(&lt;span class=s&gt;&quot;Continue&quot;&lt;/span&gt;),
            ...,

            UnregisteredStatus(_, ref reason) =&amp;gt; (*reason).clone(),
        }
    }

    &lt;b class=c&gt;&lt;i&gt;/// Get a status from the code and reason&lt;/i&gt;&lt;/b&gt;
    &lt;b&gt;pub fn&lt;/b&gt; from_code_and_reason(status: &lt;b&gt;u16&lt;/b&gt;, reason: &lt;b&gt;~str&lt;/b&gt;) -&amp;gt; Status {
        &lt;b&gt;let&lt;/b&gt; reason_lower = reason.to_ascii_lower();
        &lt;b&gt;match&lt;/b&gt; (status, reason_lower.as_slice()) {
            (&lt;span class=n&gt;100&lt;/span&gt;, &lt;span class=s&gt;&quot;continue&quot;&lt;/span&gt;) =&amp;gt; Continue,
            ...,

            (_, _) =&amp;gt; UnregisteredStatus(status, reason),
        }
    }
}

&lt;b&gt;impl&lt;/b&gt; FromPrimitive &lt;b&gt;for&lt;/b&gt; Status {
    &lt;b class=c&gt;&lt;i&gt;/// Get a *registered* status code from the number of its status code.&lt;/i&gt;&lt;/b&gt;
    &lt;b class=c&gt;&lt;i&gt;///&lt;/i&gt;&lt;/b&gt;
    &lt;b class=c&gt;&lt;i&gt;/// This will return None if an unknown code is passed.&lt;/i&gt;&lt;/b&gt;
    &lt;b class=c&gt;&lt;i&gt;///&lt;/i&gt;&lt;/b&gt;
    &lt;b class=c&gt;&lt;i&gt;/// For example, `from_u64(200)` will return `OK`.&lt;/i&gt;&lt;/b&gt;
    &lt;b&gt;fn&lt;/b&gt; from_u64(n: &lt;b&gt;u64&lt;/b&gt;) -&amp;gt; Option&amp;lt;Status&amp;gt; {
        Some(&lt;b&gt;match&lt;/b&gt; n {
            &lt;span class=n&gt;100&lt;/span&gt; =&amp;gt; Continue,
            ...,

            _   =&amp;gt; { &lt;b&gt;return&lt;/b&gt; None }
        })
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;On the surface this approach looks very well; unfortunately, it turns out that it has some problems. For now, the main thing to note is that it treats &lt;code&gt;404 Not Found&lt;/code&gt; as the same as &lt;code&gt;404 not found&lt;/code&gt; but as distinct from &lt;code&gt;404 File Not Found&lt;/code&gt;.
&lt;h2&gt;The specification&lt;/h2&gt;
&lt;p&gt;Later on we’ll look at the practical applications of these things; for now let’s take a look at what the spec says. &lt;a href=https://tools.ietf.org/html/rfc2616#section-6.1.1&gt;RFC 2616 (HTTP/1.1), section 6.1.1&lt;/a&gt;:
&lt;figure&gt;&lt;blockquote&gt;&lt;pre&gt;6.1.1 Status Code and Reason Phrase

   The Status-Code element is a 3-digit integer result code of the
   attempt to understand and satisfy the request. These codes are fully
   defined in section 10. The Reason-Phrase is intended to give a short
   textual description of the Status-Code. The Status-Code is intended
   for use by automata and the Reason-Phrase is intended for the human
   user. &lt;mark&gt;The client is not required to examine or display the Reason-&lt;/mark&gt;
   &lt;mark&gt;Phrase.&lt;/mark&gt;

   The first digit of the Status-Code defines the class of response. The
   last two digits do not have any categorization role. There are 5
   values for the first digit:

      - 1xx: Informational - Request received, continuing process

      - 2xx: Success - The action was successfully received,
        understood, and accepted

      - 3xx: Redirection - Further action must be taken in order to
        complete the request

      - 4xx: Client Error - The request contains bad syntax or cannot
        be fulfilled

      - 5xx: Server Error - The server failed to fulfill an apparently
        valid request

   The individual values of the numeric status codes defined for
   HTTP/1.1, and an example set of corresponding Reason-Phrase&apos;s, are
   presented below. &lt;mark&gt;The reason phrases listed here are only&lt;/mark&gt;
   &lt;mark&gt;recommendations -- they MAY be replaced by local equivalents without&lt;/mark&gt;
   &lt;mark&gt;affecting the protocol.&lt;/mark&gt;

      Status-Code    =
            &quot;100&quot;  ; Section 10.1.1: Continue
          | &quot;101&quot;  ; Section 10.1.2: Switching Protocols
          | &quot;200&quot;  ; Section 10.2.1: OK
&lt;em&gt;[many fields omitted for brevity]&lt;/em&gt;
          | extension-code

      extension-code = 3DIGIT
      Reason-Phrase  = *&amp;lt;TEXT, excluding CR, LF&amp;gt;

   HTTP status codes are extensible. HTTP applications are not required
   to understand the meaning of all registered status codes, though such
   understanding is obviously desirable. However, applications MUST
   understand the class of any status code, as indicated by the first
   digit, and treat any unrecognized response as being equivalent to the
   x00 status code of that class, with the exception that an
   unrecognized response MUST NOT be cached. For example, if an
   unrecognized status code of 431 is received by the client, it can
   safely assume that there was something wrong with its request and
   treat the response as if it had received a 400 status code. In such
   cases, user agents SHOULD present to the user the entity returned
   with the response, since that entity is likely to include human-
   readable information which will explain the unusual status.
&lt;/pre&gt;&lt;/blockquote&gt;&lt;/figure&gt;
&lt;h2&gt;The problem&lt;/h2&gt;
&lt;p&gt;I have marked the key phrases which the current implementation does not take properly into account. Simply, they boil down to this: &lt;strong&gt;the reason phrase is &lt;em&gt;absolutely meaningless&lt;/em&gt;&lt;/strong&gt; (sigh). I didn’t notice or didn’t pay attention to this first time around.
&lt;p&gt;I also treated the field as case insensitive, having observed things written in lowercase sometimes, and having looked at how something else, I forget what, did it. This is incorrect; while in various places the spec defines things as case insensitive, the Reason-Phrase does not fall under such a category. The Reason-Phrase, in all its uselessness, must thus be considered case sensitive.
&lt;p&gt;Well then—​can we just drop the reason phrase?
&lt;p&gt;The answer is both yes and no.
&lt;p&gt;&lt;strong&gt;Yes:&lt;/strong&gt; the integrity of the protocol itself is not affected if the reason phrase is altered; the semantics of the protocol lie purely in the Status-Code.
&lt;p&gt;&lt;strong&gt;No:&lt;/strong&gt; at the lowest level, we must provide the Reason-Phrase intact, because it &lt;em&gt;may&lt;/em&gt; be meaningful. For example, someone might be writing an HTTP inspection tool for which they wish to report this value, or someone else might be writing a proxy, where changing the value would be a highly suspect move.
&lt;p id=451&gt;&lt;strong&gt;No:&lt;/strong&gt; although the specification declares the number to be all that matters to a machine, there are cases (mostly with unregistered status codes) where people have used the same status code with multiple distinct meanings, and one may need to figure out what that meaning is. For example, the status code 451 has been used by Microsoft as “Redirect” in Exchange ActiveSync (niche, granted), and as “Unavailable for Legal Reasons” now.
&lt;p&gt;So then, how do we reconcile this?
&lt;h3&gt;The possible consequences&lt;/h3&gt;
&lt;p&gt;By the way, this &lt;em&gt;is&lt;/em&gt; a genuine problem and must be fixed; as it is, it will lead to people comparing statuses and suddenly finding bugs appearing when servers use different reason codes and all of a sudden their comparisons are not working. It might also get people comparing &lt;em&gt;codes&lt;/em&gt;, as &lt;code&gt;status.code() == 200&lt;/code&gt; if they know of this deficiency. I do not want either of these to happen.
&lt;h2&gt;Some solutions&lt;/h2&gt;
&lt;p&gt;One solution to the primary symptoms is to change equality checking on a &lt;code&gt;Status&lt;/code&gt; (the &lt;code&gt;Eq&lt;/code&gt; implementation) to just compare the Status-Code and not the Reason-Phrase. Another method can be provided to check &lt;em&gt;strict&lt;/em&gt; equality, inclusive of Reason-Phrase:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;impl&lt;/b&gt; Eq &lt;b&gt;for&lt;/b&gt; Status {
    &lt;b&gt;fn&lt;/b&gt; eq(&lt;b&gt;&amp;amp;self&lt;/b&gt;, other: &lt;b&gt;&amp;amp;&lt;/b&gt;Status) -&gt; &lt;b&gt;bool&lt;/b&gt; {
        self.code() == other.code()
    }
}

&lt;b&gt;impl&lt;/b&gt; Status {
    &lt;b&gt;fn&lt;/b&gt; strict_eq(&lt;b&gt;&amp;amp;self&lt;/b&gt;, other: &lt;b&gt;&amp;amp;&lt;/b&gt;Status) -&gt; &lt;b&gt;bool&lt;/b&gt; {
        self.code() == other.code() &amp;amp;&amp;amp; self.reason() == other.reason()
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;This doesn’t sit especially well with me (in Rust, people expect equality comparison to check everything), but it would serve the purpose.
&lt;p&gt;Another not incompatible solution is to make it so that unless the user &lt;em&gt;needs&lt;/em&gt; the reason-phrase, a known status is normalised so that &lt;code class=status-code&gt;200 All Good&lt;/code&gt; will come through as &lt;code&gt;Ok&lt;/code&gt; rather than as &lt;code&gt;UnregisteredStatus(200, ~&quot;All Good&quot;)&lt;/code&gt;. This could be arranged with a response object from a request containing two fields, &lt;code&gt;status: Status&lt;/code&gt; containing the normalised status and &lt;code&gt;raw_status: Option&amp;lt;Status&amp;gt;&lt;/code&gt; containing, if it differed, the unnormalised status. At the lowest level, of course, the status code will not be normalised.
&lt;p&gt;Either of these solutions will take care of the majority of cases, and each leaves a gap of potentially surprising (hence undesirable) behaviour. I am mildly inclined at present to go with both, but I would like opinions on the matter.
&lt;h2 id=class&gt;The status code class&lt;/h2&gt;
&lt;p&gt;&lt;em&gt;This part is still relevant in take two.&lt;/em&gt;
&lt;p&gt;One other thing I am going to add is better support for the &lt;em&gt;class&lt;/em&gt; of a status. I don’t want people to be writing &lt;code&gt;status.code() &amp;gt;= 400 &amp;amp;&amp;amp; status.code() &amp;lt; 500&lt;/code&gt;; they should instead be able to write &lt;code&gt;status.class() == ClientError&lt;/code&gt;.
&lt;h2&gt;The representation technique: enum or struct?&lt;/h2&gt;
&lt;p&gt;At present &lt;code&gt;Status&lt;/code&gt; is an enum. It could also be represented as a simple struct with plenty of constants:
&lt;figure&gt;&lt;pre&gt;&lt;code&gt;&lt;b&gt;pub struct&lt;/b&gt; Status {
    code: &lt;b&gt;u16&lt;/b&gt;,
    reason: std::str::SendStr,
}

&lt;i class=c&gt;// 1xx Informational&lt;/i&gt;
&lt;b&gt;pub static&lt;/b&gt; CONTINUE: Status = Status { code: &lt;span class=n&gt;100&lt;/span&gt;, reason: Slice(&lt;span class=s&gt;&quot;Continue&quot;&lt;/span&gt;), };
&lt;b&gt;pub static&lt;/b&gt; SWITCHING_PROTOCOLS: Status = Status { code: &lt;span class=n&gt;101&lt;/span&gt;, reason: Slice(&lt;span class=s&gt;&quot;Switching Protocols&quot;&lt;/span&gt;), };
&lt;b&gt;pub static&lt;/b&gt; PROCESSING: Status = Status { code: &lt;span class=n&gt;102&lt;/span&gt;, reason: Slice(&lt;span class=s&gt;&quot;Processing&quot;&lt;/span&gt;), };

&lt;i class=c&gt;// 2xx Success&lt;/i&gt;
&lt;b&gt;pub static&lt;/b&gt; OK: Status = Status { code: &lt;span class=n&gt;200&lt;/span&gt;, reason: Slice(&lt;span class=s&gt;&quot;OK&quot;&lt;/span&gt;), };
...&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;
&lt;p&gt;Is this feasible? Sure. Is it better? I don’t know.
&lt;ul&gt;
    &lt;li&gt;&lt;p&gt;Using a struct and constants would remove the clash on the name &lt;code&gt;Ok&lt;/code&gt; which the &lt;code&gt;Result&lt;/code&gt; type uses (it would become &lt;code&gt;OK&lt;/code&gt;).

    &lt;li&gt;&lt;p&gt;An enum uses less memory and is faster to compare on.

    &lt;li&gt;&lt;p&gt;Using a struct and constants would allow slightly better ergonomics for others using unregistered statuses (they could create their own statics, rather than needing to have a function that generated it, owing to the &lt;code&gt;~str&lt;/code&gt; contained in the current model, though that could also be changed to use &lt;code&gt;SendStr&lt;/code&gt;), leveling the field a little on what is an extremely rare case.

    &lt;li&gt;&lt;p&gt;Pattern matching doesn’t work on struct statics (or for that matter, non‐C‐style enums). (Actually, it complains “unsupported constant expr” at the static site, rather than at the match! If you’re careful, you can probably find an ICE nearby—​pnkfelix did. Bad.)
&lt;/ul&gt;
&lt;p&gt;At present I’m mildly in favour of the &lt;i&gt;status quo&lt;/i&gt;. Either way, if using &lt;code&gt;SendStr&lt;/code&gt;, the built‐in statics would still be special if I applied the normalisation technique, unless I were also to retain a mapping of IDs to statuses, (&lt;code&gt;[Option&amp;lt;&lt;b&gt;&amp;amp;&lt;i class=s&gt;&apos;static&lt;/i&gt;&lt;/b&gt; Status&amp;gt;, ..&lt;span class=n&gt;500&lt;/span&gt;]&lt;/code&gt;, it would be, I suppose. Nasty global state.)
&lt;p&gt;Bear in mind also that the method currently uses the same technique, and should, I think, use the same technique in general.
&lt;p&gt;But really, I’m open to being swayed. Do you have an opinion? Same goes for the earlier questions.
&lt;p&gt;Feel free to chip in to &lt;a href=https://www.reddit.com/r/rust/comments/23vbbt/teepee_design_a_careful_look_at_the_http11/&gt;the discussion at /r/rust&lt;/a&gt;.

			&lt;aside class=trailer&gt;
		&lt;hr&gt;
		&lt;p&gt;Comments? Questions? Corrections? If you want to contact me about anything in this post, email me at &lt;a href=&quot;mailto:me@chrismorgan.info&quot;&gt;me@chrismorgan.info&lt;/a&gt;.
	&lt;/aside&gt;
		</content>
	</entry>
	<entry xml:base="https://chrismorgan.info/blog/introducing-teepee/">
		<title type="html">Introducing Teepee: the next step for rust-http</title>
		<published>2014-04-23T00:00:00+00:00</published>
		<updated>2017-01-01T00:00:00+00:00</updated>
		<link href="https://chrismorgan.info/blog/introducing-teepee/" type="text/html"/>
		<id>http://chrismorgan.info/blog/introducing-teepee.html</id>
		<category scheme="https://chrismorgan.info/blog/tags/" term="web" label="Web" />
		<category scheme="https://chrismorgan.info/blog/tags/" term="rust" label="Rust" />
		<category scheme="https://chrismorgan.info/blog/tags/" term="teepee" label="Teepee" />
		<content type="html">
			&lt;p class=intro&gt;rust-http was but an experiment, an essay in the craft. Here, at last, is the real thing: the Teepee project, a properly engineered HTTP toolkit.
			&lt;p&gt;&lt;em&gt;This post has been sitting 90% complete for two months, and I’ve been promisng Teepee for around three months; I apologise to all those whose hopes and plans I have been delaying. Well, at least it’s here now, and it’ll be progressing faster again now.&lt;/em&gt;
&lt;aside&gt;
	&lt;p&gt;This is an ongoing series on the design of Teepee. Here are the articles on the topic in order:
	&lt;ol&gt;
		&lt;li&gt;&lt;p&gt;&lt;a href=/blog/introducing-teepee/&gt;Introducing Teepee: the next step for rust-http&lt;/a&gt; (&lt;time datetime=2014-04-23&gt;April 23&lt;/time&gt;; this article)
		&lt;li&gt;&lt;p&gt;&lt;a href=/blog/teepee-design-status-line/&gt;A careful look at the HTTP/1.1 &lt;code&gt;Status-Line&lt;/code&gt;&lt;/a&gt; (&lt;time datetime=2014-04-25&gt;April 25&lt;/time&gt;)
		&lt;li&gt;&lt;p&gt;&lt;a href=/blog/teepee-design-status-line-take-two/&gt;&lt;code&gt;Status-Line&lt;/code&gt;, take two&lt;/a&gt; (&lt;time datetime=2014-04-25&gt;April 25&lt;/time&gt;)
		&lt;li&gt;&lt;p&gt;&lt;a href=/blog/teepee-design-header-representation/&gt;Header representation&lt;/a&gt; (&lt;time datetime=2014-05-10&gt;May 10&lt;/time&gt;; this one took quite some nutting out before I finally had something that satisfied me)
		&lt;li&gt;&lt;p&gt;&lt;a href=/blog/teepee-design-method/&gt;the HTTP method&lt;/a&gt; (&lt;time datetime=2014-07-08&gt;July 8&lt;/time&gt;)
	&lt;/ol&gt;
	&lt;p&gt;More articles are coming.
	&lt;p class=alert&gt;&lt;em&gt;[2017-01-01: Teepee stalled for various technical and social reasons, mostly to do with decision paralysis; this work was subsequently taken up in the Hyper project, which has gone on to prosper. These articles are therefore useful only as a historical record.]&lt;/em&gt;
&lt;/aside&gt;
&lt;h2&gt;Background&lt;/h2&gt;
&lt;p&gt;What is currently &lt;a href=https://github.com/chris-morgan/rust-http&gt;rust-http&lt;/a&gt; was from the beginning an experimental project. I wrote it for a combination of reasons:
&lt;ul&gt;
	&lt;li&gt;&lt;p&gt;I wanted to use an HTTP library with a strong typing discipline, where things like status codes would actually &lt;em&gt;be&lt;/em&gt; status codes, not merely numbers and/or strings.
	&lt;li&gt;&lt;p&gt;Having primarily used &lt;a href=https://djangoproject.com/&gt;Django&lt;/a&gt; in the past, I had formed a vision of the web framework that I wanted. Shortly after writing down a first draft of that vision, I came across Rust again and assessed it more closely; I quickly decided that it was the first really suitable language for my vision.
	&lt;li&gt;&lt;p&gt;… but Rust had no proper HTTP library—​only a couple of toy libraries already just about to become obsolete, for these were the days when the new runtime was being finished up and the old runtime was still the default.
&lt;/ul&gt;
&lt;p&gt;As a proof of concept (especially in the extensive usage of Rust’s type system), rust-http has been successful. It’s even—​despite its limitations—​a useful library, as is evidenced by (a) people using it, and (b) no one writing any direct competitor since.&lt;!-- Leastways, none that I’ve heard of. There have been a couple of HTTP client libraries that people have written for fun (mostly bindings, which I can’t take seriously), but none that claimed to be serious. --&gt;
&lt;p&gt;Various things have changed since the initial experimentation. Most notably:
&lt;ul&gt;
	&lt;li&gt;&lt;p&gt;I understand the requirements for high-performance HTTP/1.1 and HTTP/2.0 better (I only understood HTTP/1.1 &lt;em&gt;well&lt;/em&gt; before, and I only had general notions of what the significant differences were in HTTP/2.0).
	&lt;li&gt;&lt;p&gt;I actually know Rust well now (rust-http was the first non-trivial Rust code I wrote—​it shows).
	&lt;li&gt;&lt;p&gt;The old runtime is now completely supplanted by the new runtime. (This happened some time ago and is, truth to tell, scarcely of note as concerns rust-http.)
	&lt;li&gt;&lt;p&gt;I/O errors are now explicitly handled with things returning &lt;code&gt;IoResult&lt;/code&gt;.
	&lt;li&gt;&lt;p&gt;A TcpStream can now be cloned, allowing for storing the TcpStream in both the request and the response for a server (important for squeezing optimal performance out of an HTTP/1.1 server) and also the ability to work with the same stream across multiple tasks (which is crucial for HTTP/2.0).
&lt;/ul&gt;
&lt;h2&gt;What comes next for rust-http?&lt;/h2&gt;
&lt;p&gt;Having assessed the situation and the code extant at length, I have come to the following conclusion: &lt;strong&gt;rust-http must be completely rewritten&lt;/strong&gt;.
&lt;p&gt;It is expedient for this to happen immediately rather than later, to minimise technical debt.
&lt;p&gt;The alternative was to keep a fair amount of the code base intact and alter it gradually into the new, deliberately designed form. This was my preferred approach until recently when I took a more careful look at how the existing structures would map onto what I was designing. When I did that I decided that at the very least the transfer model—​currently one layer due to what &lt;code&gt;TcpStream&lt;/code&gt; used to be and because I was at the time writing the buffered stream support myself and made the (quite natural) error of putting too much HTTP logic into it—​this transfer model needs to be two distinct layers (the stream buffer, applicable to the entire connection, and the transfer encoding, applicable to only one request) to ensure it is maintainable, plus a third for the data structures (again, that is presently more or less blended in with the rest). I am convinced that replacing this part at least wholesale is the only sensible plan.
&lt;p&gt;Beyond that, there are various other things which I would like to take this opportunity to redesign properly, such as the headers system. In the end, there is very little that I don’t want to do at least &lt;em&gt;something&lt;/em&gt; to. (I believe I’m content with the &lt;code&gt;Status&lt;/code&gt; struct, but even it will be redone with a macro rather than source code generation, for added coolness.)
&lt;p&gt;So, then, I believe a complete rewrite is in order. Parts will be used as &lt;em&gt;reference&lt;/em&gt; material, but no code will simply be copied over. It is safer thus. I will also be imposing the rule that all code that is written must include meaningful doc comments and must be tested. (Some of the key parts of rust-http are not tested; and bugs in an HTTP implementation can be a nightmare to pinpoint and fix.)
&lt;p&gt;I recognise that in this I am vulnerable to second system syndrome. This is part of the reason why I want my plans reviewed by others before building it all.
&lt;h2&gt;It’s becoming a broader project&lt;/h2&gt;
&lt;p&gt;Now that I’ve become thoroughly acquainted with Rust, I’m more sure of my footing: I want to work more with Rust in the future and I believe it will make a very good platform for web-related work; and, what’s more, I intend to be in the forefront of this brave new world where writing fast, safe and correct websites is actually popular.
&lt;p&gt;I have been mulling over what to do with rust-http. It’s got to the stage where I think separating the client and server into separate crates will be a good plan—​they have some shared things (certain traits and utility methods and all the header types), but beyond that they are largely different. I think that splitting it into &lt;code&gt;httpc&lt;/code&gt; (client) and &lt;code&gt;httpd&lt;/code&gt; (server) crates, with a common crate containing their shared dependencies and data types (perhaps &lt;code&gt;httpcommon&lt;/code&gt;), is &lt;em&gt;probably&lt;/em&gt; the way forward (this is one of the points I’m least confident about).
&lt;p&gt;In the end, this project will end up quite a bit like &lt;a href=http://spray.io/&gt;Spray&lt;/a&gt; is for Scala, and I think that having an overarching project which manages it all is probably a good idea.
&lt;p&gt;My first desire was &lt;strong&gt;http.rs&lt;/strong&gt; with its eponymous domain name, but alas! RNIDS (the operator of the .rs registry) has reserved http.rs, presumably to avoid any form of confusion.
&lt;p&gt;The name I ended up settling upon was the only one which I came up with that I really liked: &lt;strong&gt;Teepee&lt;/strong&gt;. Teepees are those American Indian tent thingies (also spelled &lt;i&gt;tipi&lt;/i&gt; or &lt;i&gt;tepee&lt;/i&gt;) but is &lt;em&gt;absolutely nothing to do with Apache HTTP server&lt;/em&gt; (that connection was suggested by a couple of people independently afterwards—​it was not my intent in any way). The real derivation of the name was the latter two letters of HTTP. The project will be based at &lt;a href=http://teepee.rs/&gt;teepee.rs&lt;/a&gt;.
&lt;aside&gt;
	&lt;h3&gt;Aside: registering .rs domains&lt;/h3&gt;
	&lt;p&gt;A .rs domain is a nice-looking thing for a Rust project, but it’s not without its caveats. I went for &lt;a href=http://istanco.rs/&gt;the cheapest registrar I could find&lt;/a&gt;. Here are some of the problems I found:
	&lt;ul&gt;
		&lt;li&gt;&lt;p&gt;Although registration is not limited to citizens of the Republic of Serbia (&lt;a href=&quot;http://www.rnids.rs/data/DOKUMENTI/Opsti akti/RNIDS-General Terms and Conditions.pdf#page=2&quot;&gt;&lt;del&gt;RNIDS General T&amp;amp;C, article 3, clause 2: “registrant can be domestic or foreign, a physical person or a legal entity”&lt;/del&gt;&lt;/a&gt; [2017-01-01: link broken; the &lt;a href=https://www.rnids.rs/registar_dokumenata/2016_05_28-general_terms-domain_registration.pdf&gt;latest version&lt;/a&gt; doesn’t seem to make it as clear, at the very least]), in practice a national personal identification number is required of the registrant (&lt;a href=&quot;http://www.rnids.rs/data/DOKUMENTI/Opsti akti/RNIDS-General Terms and Conditions.pdf#page=4&quot;&gt;&lt;del&gt;RNIDS General T&amp;amp;C, article 8, clause 2&lt;/del&gt;&lt;/a&gt;) and for this registrar at least their form required such a thing. 0000000 satisfied it and citing article 3 I’m confident that I am in fact permitted to register a .rs domain myself.
		&lt;li&gt;&lt;p&gt;Back to this particular registrar: their registration process did not use HTTPS. (Sure, the payment part did as they outsource that to 2checkout, but the part on their site did not.)
		&lt;li&gt;&lt;p&gt;And then they emailed me my password (one hundred random characters, as is my practise) in plain text.
	&lt;/ul&gt;
	&lt;p&gt;I’m not sure that I trust them much.
&lt;/aside&gt;
&lt;h2&gt;What are the important new features?&lt;/h2&gt;
&lt;ul&gt;
	&lt;li&gt;&lt;p&gt;Proper multiple HTTP version support. The library will have &lt;em&gt;good&lt;/em&gt; support for &lt;em&gt;all&lt;/em&gt; HTTP versions: 0.9 (yes! really!&lt;!-- Why? Oh, pride, of course. --&gt;), 1.0, 1.1 and 2.0.
	&lt;li&gt;&lt;p&gt;Various “bad things” will be able to be dealt with, rather than being dropped or otherwise inaccessible—​e.g. bad headers,
	&lt;li&gt;&lt;p&gt;System boundaries will be more accurately segregated, abstracting away HTTP’s transfer details more completely than it is presently done and leaving a more sound API.
	&lt;li&gt;&lt;p&gt;The tools for working with HTTP at a lower level will be more solid, and the higher level interface will sit cleanly on top of that lower level interface.
	&lt;li&gt;&lt;p&gt;In consequence, extending it will be easier; WebSocket, for example, with its &lt;code&gt;CONNECT&lt;/code&gt; upgrading, could only be implemented as a kludge in rust-http; such things will have proper support under Teepee.
	&lt;li&gt;&lt;p&gt;Unified, pure‐Rust compilation model (using custom syntax extensions in place of source code generation).
	&lt;li&gt;&lt;p&gt;Partially in consequence of all these things, Teepee’s HTTP libraries will be much easier to maintain. (I have decreed it so, and so it shall be!)
	&lt;li&gt;&lt;p&gt;Under the umbrella of the Teepee project will also exist implementations of other related specifications like &lt;a href=http://dev.w3.org/html5/websockets/&gt;WebSocket&lt;/a&gt; and &lt;a href=http://dev.w3.org/html5/eventsource/&gt;Server-Sent Events&lt;/a&gt;.
&lt;/ul&gt;
&lt;h2&gt;The new designs&lt;/h2&gt;
&lt;p&gt;I am still making some of the designs for Teepee. I will post them here as I complete them (or a little staggered); I will also be posting discussions of some of the matters that I think could do with particular discussion.
&lt;p&gt;At this point, everything can be questioned and is subject to change. Comments and criticisms are welcome as I publish the designs.
&lt;p&gt;If you wish to discuss the design, please join &lt;a href=irc://irc.mozilla.org/#teepee&gt;#teepee on irc.mozilla.org&lt;/a&gt;.
&lt;h2&gt;Are you interested?&lt;/h2&gt;
&lt;p&gt;In order to succeed, Teepee is going to need collaboration. There are a few classes of people that will be particularly valuable at this stage:
&lt;ul&gt;
	&lt;li&gt;&lt;p&gt;&lt;strong&gt;Servo developers:&lt;/strong&gt; Teepee’s HTTP client needs to meet Servo’s requirements.
	&lt;li&gt;&lt;p&gt;&lt;strong&gt;HTTP implementers:&lt;/strong&gt; for both the client and the server, to ensure everything (client and server) is implemented in a reasonable manner.
	&lt;li&gt;&lt;p&gt;&lt;strong&gt;Web app developers:&lt;/strong&gt; HTTP server design—​is it appropriate for the forms of servers that you want to write? (I’ve also got to be careful about the web framework story, that things are built in a way that doesn’t end up with frameworks reimplementing most things too much, or that it forces too much on you. That’s part of the reason for having a more layered approach this time round.)
&lt;/ul&gt;
&lt;p&gt;If you have any feedback on rust-http as it is at present and things you like about it, don’t like about it, can’t stand about it, couldn’t bear to see changed about it—​please speak up.
&lt;p&gt;If you’re interested in getting involved with Teepee or have opinions to express, please join &lt;a href=irc://irc.mozilla.org/#teepee&gt;#teepee on irc.mozilla.org&lt;/a&gt; or &lt;a href=mailto:me@chrismorgan.info&gt;drop me a line&lt;/a&gt;.
&lt;h2&gt;A little bit of personal plugging&lt;/h2&gt;
&lt;p&gt;In the long term, I hope the Teepee project as a whole to be both directly and indirectly a source of income for me and others in many and various ways (e.g. consulting, support, sponsorship of features). Whether or not this will pan out remains to be seen. At present I’m operating as a freelancer, spending most of my time working with a certain web agency (working mostly with Django), but I would love to spend more time working in/on Rust, rust-http and Teepee. If you should happen to want any development done in Rust or with rust-http, or should out of some extraordinary and inexplicable generosity desire to sponsor work on Teepee, I’m ready!
&lt;p&gt;Actively soliciting donations in this way is not something that I have observed in the Rust community yet, so I’ll make myself a test case of what the response is and whether anything happens. (Even if it’s not quite a representative case, for by my observations good HTTP support is the biggest thing people want in Rust, beyond the language itself.)
&lt;p&gt;If you want to hire or contract me for anything, please email &lt;a href=mailto:me@chrismorgan.info&gt;me@chrismorgan.info&lt;/a&gt;.
&lt;p&gt;If you want to donate to me directly to work on these things:
&lt;ul&gt;
	&lt;li&gt;&lt;a href=https://www.paypal.com/cgi-bin/webscr?cmd=_donations&amp;amp;business=me%40chrismorgan.info&amp;amp;item_name=Teepee&gt;Via PayPal&lt;/a&gt;
	&lt;li&gt;Bitcoin: &lt;a href=bitcoin:14NcYrmxFCN9wAHhxCHkyt4PU9bqnveBUj&gt;14NcYrmxFCN9wAHhxCHkyt4PU9bqnveBUj&lt;/a&gt;
	&lt;li&gt;Dogecoin (well, why not?): &lt;a href=dogecoin:DRfMMHVrnEdCmC5UaLFMp4DfMCLXMKLeSe&gt;DRfMMHVrnEdCmC5UaLFMp4DfMCLXMKLeSe&lt;/a&gt;
	&lt;li&gt;Gittip: &lt;a href=https://gittip.com/chris-morgan&gt;chris-morgan&lt;/a&gt;
&lt;/ul&gt;
&lt;p&gt;Finally: yes, this article is rather light on actual details, especially of the design. These will come in the coming weeks.

			&lt;aside class=trailer&gt;
		&lt;hr&gt;
		&lt;p&gt;Comments? Questions? Corrections? If you want to contact me about anything in this post, email me at &lt;a href=&quot;mailto:me@chrismorgan.info&quot;&gt;me@chrismorgan.info&lt;/a&gt;.
	&lt;/aside&gt;
		</content>
	</entry>
	<entry xml:base="https://chrismorgan.info/blog/rust-docs-vision-presentation/">
		<title type="html">A broad vision for the Rust docs stack</title>
		<published>2013-12-19T00:00:00+00:00</published>
		<updated>2013-12-19T00:00:00+00:00</updated>
		<link href="https://chrismorgan.info/blog/rust-docs-vision-presentation/" type="text/html"/>
		<id>http://chrismorgan.info/blog/rust-docs-vision-presentation.html</id>
		<category scheme="https://chrismorgan.info/blog/tags/" term="rust" label="Rust" />
		<category scheme="https://chrismorgan.info/blog/tags/" term="documentation" label="Documentation" />
		<category scheme="https://chrismorgan.info/blog/tags/" term="presentations" label="Presentations" />
		<content type="html">
			&lt;p class=intro&gt;A presentation that I made to the San Fransisco Bay Area Rust meetup about the implementation side of Rust docs, and what I think should be used.
			&lt;p&gt;Yesterday (Tuesday evening in America, Wednesday afternoon in Australia) I gave a presentation to the San Fransisco Bay Area Rust meetup on the topic of the Rust documentation; Steve Klabnik, who spoke before me, dealt mostly with the contents of the documentation and I dealt much more with the tech stack which I thought would best achieve this goal (we agreed pretty well on the broad goals of the documentation).
&lt;p&gt;I give especial thanks to Erick Tryzelaar for going to the trouble of arranging for this presentation to occur and for ironing out all the issues that arose in SF.
&lt;h2&gt;The slides&lt;/h2&gt;
&lt;p&gt;&lt;a href=https://air.mozilla.org/rust-meetup-december-2013/&gt;A video recording of the presentation is available on Air Mozilla&lt;/a&gt;; my talk begins at about 34:30 and continues until 55:00.&lt;!-- I’m not embedding it, though, because it only lets me do that at 640×480 rather than being responsive, nor does it let me specify the time range that I want played, so I’m just sitting here sulking. --&gt; The slides below are sufficient to get the significant majority of the important stuff from the presentation if you prefer.
&lt;!-- On the topic of video, I tried making a recording of myself for a backup plan, but it didn’t pan out particularly well without any audience—​even if I couldn’t actually see or hear the audience when I did finally present. --&gt;
&lt;figure&gt;
	&lt;object id=slides type=image/svg+xml data=&quot;rust-docs-vision-presentation.svg&quot;&gt;
		&lt;a href=&quot;rust-docs-vision-presentation.svg&quot;&gt;View the slides here&lt;/a&gt; (SVG; you’ll need a “modern” browser to view them, or you could ask me to make a PDF of them for you)
	&lt;/object&gt;
	&lt;figcaption&gt;&lt;p&gt;The slides. Click, tap, arrow keys—​whatever you like.&lt;!-- … except hjkl --&gt; &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;script&gt;
	var slides = document.getElementById(&apos;slides&apos;);
	if (slides.requestFullscreen || slides.mozRequestFullScreen || slides.webkitRequestFullscreen) {
		button = document.createElement(&apos;button&apos;);
		button.textContent = &apos;Show fullscreen&apos;;
		button.onclick = function() {
			slides.focus();
			if (slides.requestFullscreen) {
				slides.requestFullscreen();
			} else if (slides.mozRequestFullScreen) {
				slides.mozRequestFullScreen();
			} else if (slides.webkitRequestFullscreen) {
				slides.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
			}
		}
		slides.nextElementSibling.lastChild.appendChild(button);
	}
&lt;/script&gt;
&lt;p&gt;These slides are best viewed in Firefox. (I just tried Chromium and it renders the SVG incorrectly in a number of places—​collapsing multiple sequential spaces into one in text, selecting the wrong font weight if you have the Ubuntu font installed locally, getting manual character offsets on the wrong characters in one of the slides… not good.)
&lt;p&gt;If you’re interested in the tech that went into the slides themselves, &lt;a href=/blog/rust-docs-vision-presentation-internals/&gt;I’ve written an article on that, too&lt;/a&gt;.
&lt;p&gt;Now onto some of the other things I wanted to add more about in the languages section.
&lt;h2&gt;The Java documentation&lt;/h2&gt;
&lt;p&gt;Try to find the official Java documentation. Some places you might start:
&lt;ul&gt;
	&lt;li&gt;&lt;a href=https://www.java.com/&gt;https://www.java.com/&lt;/a&gt;: … well, if you dig deep enough you’ll find something (start with that tiny “developers” link in the footer).
	&lt;li&gt;&lt;a href=https://duckduckgo.com/?q=java+docs&gt;https://duckduckgo.com/?q=java+docs&lt;/a&gt;: showing mostly API documentation.
	&lt;li&gt;&lt;a href=https://encrypted.google.com/search?q=java%20docs&gt;https://encrypted.google.com/search?q=java%20docs&lt;/a&gt;: ditto.
&lt;/ul&gt;
&lt;p&gt;As I observed, hunt hard enough and you’ll find &lt;a href=https://docs.oracle.com/javase/&gt;https://docs.oracle.com/javase/&lt;/a&gt;. It doesn’t try particularly hard to head you in the right direction, but if you’re persistent
you’ll find there are three main things it’s got.
&lt;ol&gt;
	&lt;li&gt;The root of the docs: &lt;a href=https://docs.oracle.com/javase/7/docs/index.html&gt;https://docs.oracle.com/javase/7/docs/index.html&lt;/a&gt;
		&lt;p&gt;OK, so… now where do I go? Oh! The table cells are clickable. How about we try &lt;a href=https://docs.oracle.com/javase/7/docs/technotes/guides/io/index.html&gt;Input/Output&lt;/a&gt;? Now what do we have?
		&lt;ul&gt;
			&lt;li&gt;A few links to things in different places—​the tutorials, for the odd topic a tech guide (often about actually implementing the feature itself rather than using it)
			&lt;li&gt;API documentation links
			&lt;li&gt;If you’re lucky, an example or two
			&lt;li&gt;And a bit of changelog
		&lt;/ul&gt;
		&lt;p&gt;And this is &lt;em&gt;all&lt;/em&gt; of the Java Platform Standard Edition 7 Documentation.

	&lt;li&gt;The official tutorials: &lt;a href=https://docs.oracle.com/javase/tutorial/&gt;https://docs.oracle.com/javase/tutorial/&lt;/a&gt;
		&lt;p&gt;They’re decent for learning something, but frankly, I don’t have time to learn that thing. I already know Java, right? I just want to find out how to do this one particular thing. The tutorials also make dubious reference material, because they’re not geared to minimal examples; rather they’re designed for linear progression; the right one can also be difficult to find, assuming it even exists.
		&lt;p&gt;They’re simply not designed for discovery. Everyone already knows Java or they’re learning it at University (also known as “college” or “school”) from other sources, and so won’t &lt;em&gt;need&lt;/em&gt; them.

	&lt;li&gt;The API documentation: &lt;a href=https://docs.oracle.com/javase/7/docs/api/index.html&gt;https://docs.oracle.com/javase/7/docs/api/index.html&lt;/a&gt;
		&lt;p&gt;This is the heavy hitter of the lot, and the heavy hitter in more ways than one.
		&lt;p&gt;This is somehow the panacea for everything; you want to know what something can do? Here! Here’s what it can do!
		&lt;p&gt;Now read this forty page document which explains what each method does and gain enlightenment.
&lt;/ol&gt;
&lt;p&gt;I come away not particularly impressed. Yes, the Java community can produce fairly good API documentation as they go, but it’s not designed for &lt;em&gt;learning&lt;/em&gt;, which is a problem.
&lt;h3&gt;An example&lt;/h3&gt;
&lt;p&gt;I’ll draw this all together with an example; in this past semester for a Computer Graphics unit (“course” for Americans) I was doing some OpenGL stuff in Java and I wanted a spinner (you know, the number entry field with arrows) for the window chrome; I wanted to find something in the official docs about them.
&lt;p&gt;I found &lt;a href=https://docs.oracle.com/javase/tutorial/uiswing/components/spinner.html&gt;a tutorial about them&lt;/a&gt;, but I really had no time to learn it that way. I had my project set up the way it was set up and setting up a new project for that stuff and going through it in a linear fashion simply couldn’t cut it—​that would, all up, have taken hours.
&lt;p&gt;Well, how about the &lt;a href=https://docs.oracle.com/javase/7/docs/api/javax/swing/JSpinner.html&gt;JSpinner API documentation&lt;/a&gt;?
&lt;p&gt;… that was even worse.
&lt;p&gt;That’s why I conclude that &lt;em&gt;pragmatism&lt;/em&gt; is what the Java docs are lacking.
&lt;p&gt;(P.S. Remember that javadoc was once a pretty radical thing; Java &lt;em&gt;has&lt;/em&gt; played a significant part in improving documentation standards, and the existence of javadoc means that Java projects do tend to have at least basic documentation. It’s really isn’t all bad.)
&lt;p&gt;And as for that quote I used on pragmatism, here’s the source:
&lt;blockquote&gt;
	&lt;p&gt;What sold me on Rust is how insanely practical it is…
	&lt;p&gt; — &lt;cite&gt;&lt;a href=https://www.reddit.com/r/rust/comments/1s9y7o/less_is_more_lambda_the_ultimate/cdvhhfq&gt;/u/Jurily on Reddit&lt;/a&gt;&lt;/cite&gt;
&lt;/blockquote&gt;
&lt;h2&gt;The Python docs&lt;/h2&gt;
&lt;p&gt;Start at &lt;a href=https://python.org/&gt;https://python.org/&lt;/a&gt;. Look in the navigation. Ah! There’s “documentation”.
&lt;p&gt;&lt;a href=https://python.org/doc/&gt;https://python.org/doc/&lt;/a&gt;. That’s a nice and easy‐to‐read thing but pretty much everything you could want is there and clear.
&lt;p&gt;Let’s try the Python 3 documentation. &lt;a href=https://docs.python.org/3/&gt;https://docs.python.org/3/&lt;/a&gt;. Again, everything is nice and clear.
&lt;p&gt;Do I want to look at the standard library reference? &lt;a href=https://docs.python.org/3/library/index.html&gt;https://docs.python.org/3/library/index.html&lt;/a&gt;
&lt;p&gt;This is no auto‐generated javadoc; this is curated. Look through it all; I don’t mind what you look at there because I know it’s all pretty good.
&lt;p&gt;There’s a general pattern of things that I want to point out:
&lt;ul&gt;
	&lt;li&gt;good explanation at the top of the concepts and functionality;
	&lt;li&gt;genuine usage example—​as in, bits of code that you can copy and verify to be doing what you want;
	&lt;li&gt;directing you to other good third party sources—​even going so far as to say things like “this is a common use case, but it’s not in the standard library; here’s the technique most people are using” (Java, by comparison, is fairly leery of third‐party links);
	&lt;li&gt;oh yes, actually documenting the API as well (of course).
&lt;/ul&gt;
&lt;p&gt;A few interesting examples (but don’t &lt;em&gt;just&lt;/em&gt; look at these ones!):
&lt;ul&gt;
	&lt;li&gt;&lt;a href=https://docs.python.org/3/library/subprocess.html&gt;&lt;code&gt;subprocess&lt;/code&gt;&lt;/a&gt; uses sound categorisation of things rather than alphabetical order or mere order in source. It also gives good examples, comparisons with what other people may be used to, security considerations, &lt;i&gt;&amp;amp;c.&lt;/i&gt;
	&lt;li&gt;&lt;a href=https://docs.python.org/3/library/itertools.html&gt;&lt;code&gt;itertools&lt;/code&gt;&lt;/a&gt; uses tables to concisely demonstrate the information that most people will come for, before then proceeding to more traditional documentation, followed at the end by a large number of recipes. (Don’t constrain yourself to text! Something that would be useful in places in the Python docs is images. Yes, you can use images in these sorts of documentation; for comparison, &lt;a href=https://portableapps.com/manuals/PortableApps.comLauncher/topics/languages.html&gt;here is one I prepared a few years ago&lt;/a&gt;, when using Sphinx in the PortableApps.com Launcher documentation; a flowchart augments the textual description of the same thing.
	&lt;li&gt;&lt;a href=https://docs.python.org/3/library/collections.html&gt;&lt;code&gt;collections&lt;/code&gt;&lt;/a&gt; explains the purposes, gives usage examples, gives alternative data structures and implementations, provides links for implementations in other languages or for old versions of Python, explains briefly where it’s good or bad to use this, and so on and so forth.
&lt;/ul&gt;
&lt;p&gt;A couple of other important things it shows are the &lt;a href=https://docs.python.org/3/py-modindex.html&gt;module index&lt;/a&gt; (we can make whatever indexes we desire) and &lt;a href=https://docs.python.org/3/search.html?q=ECONNABORTED&gt;search&lt;/a&gt;.

			&lt;aside class=trailer&gt;
		&lt;hr&gt;
		&lt;p&gt;Comments? Questions? Corrections? If you want to contact me about anything in this post, email me at &lt;a href=&quot;mailto:me@chrismorgan.info&quot;&gt;me@chrismorgan.info&lt;/a&gt;.
	&lt;/aside&gt;
		</content>
	</entry>
</feed>
