\documentclass[11pt]{article}  
\usepackage{verbatim}
\usepackage{ifpdf}
\usepackage{url}
\usepackage{setspace}
\usepackage{cite}
\def\citepunct{, }
\usepackage{listings}

\begin{document}



<p>Title: Class 2: Getting Started with Rust Date: 2013-09-02 Category: Classes Tags: operating system, rust Author: David Evans</p>
<h1 id="action-items">Action Items</h1>
<div class="todo">
<ul>
<li> 
<p>If you think you are in the class but did not already submit a <a
href="https://docs.google.com/forms/d/1j_G0FEK6Sp7FlEMbQmwA22Tcfm3YRmWcX8h9sjIasdI/viewform">cs4414 student survey</a>, you need to meet with me this week. I will assume only students who submitted the survey are actually in the class, and only those students will be assigned teammates for Problem Set 2.</p>
<li> 
You should have at least completed the Exercises for <a
href="http://www.cs.virginia.edu/~evans/cs4414-fall2013/pages/ps1.html">Problem Set 1</a> before Thursday's class.
</ul>
</div>

<h2 id="programming-languages">Programming Languages</h2>
<p>Why are there so many programming languages?</p>
<div class="gap"></div>

<ul>
<li><p>Languages change the way we <strong>think</strong>.</p></li>
<li>Languages provide <strong>abstractions</strong> for machine resources. The abstractions they provide are engineering tradeoffs between:
<ul>
<li><em>expressiveness</em> and <em>&quot;truthiness&quot;</em></li>
<li><em>freedom</em> and <em>safety</em></li>
<li><em>flexibility</em> and <em>simplicity</em></li>
<li><em>efficiency</em> and <em>ease-of-use</em></li>
</ul></li>
</ul>
<p>Which of these should we prefer for a programming language for systems programming?</p>
<div class="gap"></div>

<p>What's the difference between a language and an operating system?</p>
<div class="gap"></div>

<h2 id="rust">Rust</h2>
<p><a href="http://www.rust-lang.org">Rust</a> is a systems programming language developed by <a href="http://www.mozilla.org/en-US/research/">Mozilla Research</a>. It is a new and immature language: the release we are using is Version 0.7 (released in July 2013).</p>
<p>Rust is designed with a particular focus on providing <em>safety</em> and <em>efficiency</em>. This means it provides programmers with a lot of control over how memory is managed, but without the opportunity to shoot yourself in the foot so readily provided by C/C++. Much of the design is driven by the needs of <a href="https://github.com/mozilla/servo">Servo</a>, an experimental, highly-parallelizable web browser engine.</p>
<p>Today, we will introduce some of the basics you'll need to get started programming in Rust (and for completing PS1). In later classes, we'll look more deeply as some of the most interesting aspects of how types, memory management, and concurrency work in Rust.</p>
<h2 id="first-rust-program">First Rust Program</h2>
<p>Let's get started with a simple Rust program:</p>
<pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> max(a: <span class="kw">int</span>, b: <span class="kw">int</span>) -&gt; <span class="kw">int</span> {
    <span class="kw">if</span> a &gt; b {
        a
    } <span class="kw">else</span> {
        b
    }
}

<span class="kw">fn</span> main() {
    println(fmt!(<span class="st">&quot;Max: %?&quot;</span>, max(<span class="dv">3</span>, <span class="dv">4</span>)));
}</code></pre>
<p>If you are familiar with C (or at least C++) and Java, most of this should look fairly familiar, but some things a bit unusual.</p>
<h2 id="statements-and-expressions">Statements and Expressions</h2>
<p>Hypothesized Rust grammar (the Rust manual has a grammar, but &quot;looking for consistency in the manual's grammar is bad: it's entirely wrong in many places&quot;):</p>
<pre><code>:::BNF
IfExpression ::= &lt;b&gt;if&lt;/b&gt; Expression Block [ &lt;b&gt;else&lt;/b&gt; Block ]
Block ::= &lt;b&gt;{&lt;/b&gt; [Statement&lt;sup&gt;*&lt;/sup&gt; Expr] &lt;b&gt;}&lt;/b&gt;
Expression ::= Block    
     </code></pre>
<p>How is the meaning of <code>;</code> different in Rust and Java?</p>
<div class="gap"></div>

<h2 id="higher-order-functions">Higher-Order Functions</h2>
<p>We can make new functions directly:</p>
<pre><code>:::BNF
LambdaExpression ::= &lt;b&gt;|&lt;/b&gt; Parameters &lt;b&gt;|&lt;/b&gt; Block</code></pre>
<p>Define a function, <code>make_adder(int) -&gt; ~fn(int) -&gt; int</code>, that takes an integer as input and returns a function that takes and int and returns the sum of the original and input int.</p>
<div class="gap"></div>

<pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> ntimes(f: <span class="kw">extern</span> <span class="kw">fn</span>(<span class="kw">int</span>) -&gt; <span class="kw">int</span>, times: <span class="kw">int</span>) -&gt; ~<span class="kw">fn</span>(<span class="kw">int</span>) -&gt; <span class="kw">int</span> {



}


<span class="kw">fn</span> double(a: <span class="kw">int</span>) -&gt; <span class="kw">int</span> {
    a * <span class="dv">2</span>
}

<span class="kw">fn</span> main() {
    <span class="kw">let</span> quadruple = ntimes(double, <span class="dv">2</span>);
    println(fmt!(<span class="st">&quot;quad: %?&quot;</span>, quadruple(<span class="dv">2</span>))); <span class="co">// 8</span>
}</code></pre>
<h2 id="reading-a-file">Reading a File</h2>
<p>We will use the <a href="http://static.rust-lang.org/doc/0.7/std/io.html#function-file_reader"><code>std:io::file_reader</code></a> function to read a file (as you'll note if you follow the link, the current Rust documentation is very sparse and incomplete!):</p>
<pre><code>:::rust
fn file_reader(path: &amp;Path) -&gt; Result&lt;@Reader, ~str&gt;</code></pre>
<p>This function takes as <a href="http://static.rust-lang.org/doc/0.7/std/path.html"><code>Path</code></a> as input and returns as <code>Result&lt;@Reader, ~str&gt;</code>.</p>
<p><a href="http://static.rust-lang.org/doc/0.7/std/result.html#enum-result">Result</a> is an <a href="http://static.rust-lang.org/doc/0.7/rust.html#enumerated-types">enumerated type</a> with two type parameters. Its value is either:</p>
<ul>
<li><code>Ok(T)</code> - A successful value of type <code>T</code></li>
<li><code>Err(U)</code> - An error of type <code>U</code></li>
</ul>
<p>Result types provide a way of dealing with errors without all the uncertainty and complexity of exceptions. So, in this case, <code>Result&lt;@Reader, ~str&gt;</code> is either a <code>@Reader</code>, corresponding to successfully opening the file, or an <code>~str</code>, corresponding to an error message when the file cannot be opened. (The <code>@</code> and <code>~</code> indicate different types of pointers; we'll get to that later.)</p>
<p>Why are (Java-style) exceptions a bad thing in a language focused on safety?</p>
<div class="gap"></div>

<p>We can use <a href="http://static.rust-lang.org/doc/tutorial.html#control-structures">pattern matching</a> to control execution based on the type of the <code>Enum</code>:</p>
<pre class="sourceCode rust"><code class="sourceCode rust"><span class="kw">fn</span> load_file(pathname : ~<span class="kw">str</span>) -&gt; ~[~<span class="kw">str</span>] {
    <span class="kw">let</span> filereader : <span class="kw">Result</span>&lt;@Reader, ~<span class="kw">str</span>&gt; = io::file_reader(~path::Path(pathname));
    <span class="kw">match</span> filereader {
        <span class="kw">Ok</span>(reader) =&gt; reader.read_lines(),
        <span class="kw">Err</span>(msg) =&gt; <span class="kw">fail</span>!(<span class="st">&quot;Cannot open file: &quot;</span> + msg),
    }
}</code></pre>
<p>Note that <code>match</code> is an expression just like <code>if</code>! There's no need to <code>return reader.read_lines()</code>, its the value of the expression that is the body of <code>load_file</code>. (Also, note that this isn't a smart way to do this for large files, since it requires storing the whole file in memory.)</p>
<p>Match expressions must be <em>complete</em>:</p>
<pre class="sourceCode rust"><code class="sourceCode rust"></code></pre>
<p>Match predicates can be arbitrary expressions: ``` fn collatz(n : int) -&gt; int { let mut count = 0; let mut current = n;</p>
<pre><code>while current != 1 {
    current = 
        match current {
           current if current % 2 == 0 =&gt; current / 2,
           _ =&gt; 3 * current + 1
        };
    count += 1
}
count</code></pre>
<p>}</p>
<p>fn main() { for std::int::range(1, 100) |i| { println(fmt!(&quot;hailstone %d = %d&quot;, i, collatz(i))); } } ```</p>
<h2 id="ways-to-get-help">Ways to Get Help</h2>
<ol style="list-style-type: decimal">
<li><p>Search engines are your friend: <a href="https://www.google.com/#q=reading+files+in+rust">reading files in rust</a> Hints: unfortunately &quot;rust&quot; is a common word, and not (yet) a widely used language. If you know a specific function, easy to search on that (but harder if you don't know).</p></li>
<li><p><a href="http://stackoverflow.com/questions/tagged/rust">Stackoverflow</a> can be great...but not much Rust discussion yet.</p></li>
<li><p><strong>Experiment!</strong> The compiler is very helpful, and mostly provides good error and warning messages. Use <code>fmt!(&quot;%?&quot;, x)</code> to print out (almost) anything.</p></li>
<li>Ask for help:</li>
</ol>
<ul>
<li><a href="https://piazza.com/virginia/fall2013/cs4414">Piazza course forum</a></li>
<li><a href="|filename|../../pages/tools/irc.md">IRC</a> - most of the Rust developers hang out there and are quick to answer questions</li>
</ul>
<p>If you figure something useful out that is not well documented, <strong>document it</strong>! Help out the class, the Rust community, and gain fame and fortune for yourself by creating good documentation and posting it in useful ways (course Piazza forum, your blog, <a href="http://www.reddit.com/r/rust/">reddit</a>, etc.).</p>

%

\end{document}
