<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Shaun Hamilton - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Shaun Hamilton - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 29 May 2026 23:03:28 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/sky020/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Embedded Rust Programming on Raspberry Pi Zero W ]]>
                </title>
                <description>
                    <![CDATA[ Embedded programming in Rust requires a whole new knowledge base. Using a Raspberry Pi Zero W, you can quickly get up and running with embedded Rust.  Starting with an embedded "Hello World" equivalent, and advancing to a text-to-morse-code translato... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/embedded-rust-programming-on-raspberry-pi-zero-w/</link>
                <guid isPermaLink="false">66ace42a106bc8d5a4eb36f6</guid>
                
                    <category>
                        <![CDATA[ embedded systems ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Raspberry Pi ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Rust ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Shaun Hamilton ]]>
                </dc:creator>
                <pubDate>Thu, 09 Jun 2022 15:37:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/06/rpi-rust.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Embedded programming in Rust requires a whole new knowledge base. Using a Raspberry Pi Zero W, you can quickly get up and running with embedded Rust. </p>
<p>Starting with an embedded <em>"Hello World"</em> equivalent, and advancing to a text-to-morse-code translator, this article will walk you through the process.</p>
<ul>
<li><a class="post-section-overview" href="#heading-how-to-set-up-the-pi">How to Set Up the Pi</a><ul>
<li><a class="post-section-overview" href="#heading-format-the-sd-card">Format the SD Card</a></li>
<li><a class="post-section-overview" href="#heading-flash-the-distribution">Flash the Distribution</a><ul>
<li><a class="post-section-overview" href="#heading-configure-wifi-and-ssh">Configure Wifi and SSH</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-complete-the-circuit">Complete the Circuit</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-set-up-cross-compilation">How to Set Up Cross Compilation</a><ul>
<li><a class="post-section-overview" href="#heading-install-the-target">Install the Target</a></li>
<li><a class="post-section-overview" href="#heading-specify-the-linker">Specify the Linker</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-program-an-embedded-hello-world">How to Program an Embedded "Hello World"</a><ul>
<li><a class="post-section-overview" href="#heading-successfully-exit-the-program">Successfully Exit the Program</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-cross-compile-the-program">How to Cross Compile the Program</a></li>
<li><a class="post-section-overview" href="#heading-how-to-transfer-the-binary-to-the-pi">How to Transfer the Binary to the Pi</a></li>
<li><a class="post-section-overview" href="#heading-how-to-ssh-into-the-pi">How to SSH into the Pi</a><ul>
<li><a class="post-section-overview" href="#heading-run-the-program">Run the Program</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-code-a-text-to-morse-code-translator">How to Code a Text-to-Morse-Code Translator</a></li>
<li><a class="post-section-overview" href="#heading-appendix">Appendix</a><ul>
<li><a class="post-section-overview" href="#heading-targets-1">Targets</a></li>
</ul>
</li>
</ul>
<h2 id="heading-how-to-set-up-the-pi">How to Set Up the Pi</h2>
<h3 id="heading-format-the-sd-card">Format the SD Card</h3>
<p>Use the Raspberry Pi Imager which can be downloaded from the <a target="_blank" href="https://www.raspberrypi.com/software/">Raspberry Pi Software Webpage</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/rpi-imager.png" alt="rpi-imager" width="600" height="400" loading="lazy"></p>
<h3 id="heading-flash-the-distribution">Flash the Distribution</h3>
<p>A distribution I'd suggest is <a target="_blank" href="https://www.raspberrypi.com/software/operating-systems/">Raspberry Pi OS Lite</a>. This is a <em>headless</em> distribution, which means it does not come with a GUI.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/rpi-imager-os.png" alt="rpi-imager-os" width="600" height="400" loading="lazy"></p>
<h4 id="heading-configure-wifi-and-ssh">Configure Wifi and SSH</h4>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/rpi-imager-ssh.png" alt="rpi-imager-ssh" width="600" height="400" loading="lazy"></p>
<p>Once that is done, you can insert the SD card into the Raspberry Pi, and power it up.</p>
<h3 id="heading-complete-the-circuit">Complete the Circuit</h3>
<p><strong>Circuit Diagram</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/rpi-circuit.png" alt="rpi-circuit" width="600" height="400" loading="lazy"></p>
<p><strong>Pi Pinout</strong></p>
<p>Connect negative to ground, and positive to BCM pin 17 as shown below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/rpi-pinout.png" alt="rpi-pinout" width="600" height="400" loading="lazy"></p>
<p>The pinout can be seen here: https://pinout.xyz/</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/IMG_3418-1-.JPG" alt="IMG_3418-1-" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-set-up-cross-compilation">How to Set Up Cross Compilation</h2>
<h3 id="heading-install-the-target">Install the Target</h3>
<p>Use <code>rustup</code> to install the necessary target for your Raspberry Pi:</p>
<pre><code class="lang-bash">my-pc$ rustup add target arm-unknown-linux-gnueabihf
</code></pre>
<p><a class="post-section-overview" href="#heading-targets-1">Appendix</a> for more information about targets in Rust.</p>
<h3 id="heading-specify-the-linker">Specify the Linker</h3>
<p>Download the <code>raspberrypi/tools</code> repository into a directory named <code>rpi_tools</code>:</p>
<pre><code class="lang-bash">my-pc:~ $ git <span class="hljs-built_in">clone</span> https://github.com/raspberrypi/tools <span class="hljs-variable">$HOME</span>/rpi_tools
</code></pre>
<p>Edit the <code>~/.cargo/config</code> file using your favourite text editor:</p>
<pre><code class="lang-bash">my_pc:~ $ sudo nano ~/.cargo/config
</code></pre>
<p>Tell Cargo to use a specific linker version for your target:</p>
<pre><code class="lang-conf">[target.arm-unknown-linux-gnueabihf]
linker = "/rpi_tools/arm-bcm2708/arm-rpi-4.9.3-linux-gnueabihf/bin/arm-linux-gnueabihf-gcc"
</code></pre>
<h2 id="heading-how-to-program-an-embedded-hello-world">How to Program an Embedded "Hello World"</h2>
<p>Start by creating a new Rust project, and opening the <code>main.rs</code> file in your favourite text editor:</p>
<pre><code class="lang-bash">my-pc:~ $ cargo new blink
my-pc:~ $ <span class="hljs-built_in">cd</span> blink
my-pc:~/blink $ nano src/main.rs
</code></pre>
<p>Import the <code>rust_gpiozero</code> crate, and program an LED to alternate between on and off every second:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> rust_gpiozero::*;

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-comment">// Create a new LED attached to Pin 17</span>
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> led = LED::new(<span class="hljs-number">17</span>);

    led.blink(<span class="hljs-number">1.0</span>, <span class="hljs-number">1.0</span>);

    led.wait();
}
</code></pre>
<p>Be sure to add the dependency to the <code>Cargo.toml</code> file:</p>
<pre><code class="lang-toml"><span class="hljs-section">[dependencies]</span>
<span class="hljs-attr">rust-gpiozero</span> = <span class="hljs-string">"0.2.1"</span>
</code></pre>
<h3 id="heading-successfully-exit-the-program">Successfully Exit the Program</h3>
<p>Since <code>rustc 1.61.0</code> <sup>[<a target="_blank" href="https://doc.rust-lang.org/stable/std/process/struct.ExitCode.html">1</a>]</sup>, you can use the <code>std::process::ExitCode</code> struct to specify the status code returned to the process' parent:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::process::ExitCode;
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() -&gt; ExitCode {
    <span class="hljs-comment">// ...</span>
    <span class="hljs-keyword">if</span> error {
      <span class="hljs-keyword">return</span> ExitCode::from(<span class="hljs-number">1</span>);
    }
    ExitCode::SUCCESS
}
</code></pre>
<p>Otherwise, you can simply return a <code>Result</code>:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() -&gt; <span class="hljs-built_in">Result</span>&lt;(), std::io::Error&gt; {
  <span class="hljs-comment">// ...</span>
  <span class="hljs-literal">Ok</span>(())
}
</code></pre>
<h2 id="heading-how-to-cross-compile-the-program">How to Cross Compile the Program</h2>
<p>Build a release of your program, targeting the required architecture:</p>
<pre><code class="lang-bash">my-pc:~/blink $ cargo build --release --target=arm-unknown-linux-gnueabihf
</code></pre>
<h2 id="heading-how-to-transfer-the-binary-to-the-pi">How to Transfer the Binary to the Pi</h2>
<p>Use <code>scp</code> to transfer the compiled binary from your host computer to the Raspberry Pi over SSH:</p>
<pre><code class="lang-bash">my-pc:~/blink $ scp target/arm-unknown-linux-gnueabihf/release/blink pi@192.168.1.199:~/blink
</code></pre>
<p><strong>Note:</strong> The local IP of your Pi will likely be different.</p>
<h2 id="heading-how-to-ssh-into-the-pi">How to SSH into the Pi</h2>
<p>SSH and log in to the Raspberry Pi via its local IP address:</p>
<pre><code class="lang-bash">my-pc:~ $ ssh pi@192.168.1.199
</code></pre>
<h3 id="heading-run-the-program">Run the Program</h3>
<p>From the Raspberry Pi, run the compiled binary:</p>
<pre><code class="lang-bash">pi:~ $ ./blink
</code></pre>
<h2 id="heading-how-to-code-a-text-to-morse-code-translator">How to Code a Text-to-Morse-Code Translator</h2>
<p>Here is an example of an application that reads the stdin line by line, translates the input into Morse Code, and toggles the LED on and off based on the Morse Code for the characters.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> rust_gpiozero::*;
<span class="hljs-keyword">use</span> std::io::{BufRead, <span class="hljs-keyword">self</span>};
<span class="hljs-keyword">use</span> std::collections::HashMap;
<span class="hljs-keyword">use</span> std::thread::sleep;
<span class="hljs-keyword">use</span> std::time::Duration;

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() -&gt; <span class="hljs-built_in">Result</span>&lt;(), std::io::Error&gt; {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Starting...\n- Type in text to turn into Morse Code\n- Type `quit()` to quit\n"</span>);
    <span class="hljs-comment">// Create a new LED attached to Pin 17</span>
    <span class="hljs-keyword">let</span> led = LED::new(<span class="hljs-number">17</span>);

    <span class="hljs-comment">/// Length of a dot in milliseconds</span>
    <span class="hljs-keyword">const</span> DOT_DELAY: <span class="hljs-built_in">u64</span> = <span class="hljs-number">80</span>;
    <span class="hljs-comment">/// Length of a dash in milliseconds</span>
    <span class="hljs-keyword">const</span> DASH_DELAY: <span class="hljs-built_in">u64</span> = DOT_DELAY * <span class="hljs-number">3</span>;
    <span class="hljs-comment">/// Delay between inputs in milliseconds</span>
    <span class="hljs-keyword">const</span> PUSH_DELAY: <span class="hljs-built_in">u64</span> = DOT_DELAY;
    <span class="hljs-comment">/// Delay between letters in milliseconds</span>
    <span class="hljs-keyword">const</span> LETTER_DELAY: <span class="hljs-built_in">u64</span> = DOT_DELAY * <span class="hljs-number">3</span>;
    <span class="hljs-comment">/// Delay between words in milliseconds</span>
    <span class="hljs-keyword">const</span> WORD_DELAY: <span class="hljs-built_in">u64</span> = DOT_DELAY * <span class="hljs-number">7</span>;

    <span class="hljs-keyword">let</span> morse_code_alphabet: HashMap&lt;<span class="hljs-built_in">char</span>, &amp;<span class="hljs-symbol">'static</span> <span class="hljs-built_in">str</span>&gt; =
    [
        (<span class="hljs-string">'a'</span>, <span class="hljs-string">".-"</span>),
        (<span class="hljs-string">'b'</span>, <span class="hljs-string">"-..."</span>),
        (<span class="hljs-string">'c'</span>, <span class="hljs-string">"-.-."</span>),
        (<span class="hljs-string">'d'</span>, <span class="hljs-string">"-.."</span>),
        (<span class="hljs-string">'e'</span>, <span class="hljs-string">"."</span>),
        (<span class="hljs-string">'f'</span>, <span class="hljs-string">"..-."</span>),
        (<span class="hljs-string">'g'</span>, <span class="hljs-string">"--."</span>),
        (<span class="hljs-string">'h'</span>, <span class="hljs-string">"...."</span>),
        (<span class="hljs-string">'i'</span>, <span class="hljs-string">".."</span>),
        (<span class="hljs-string">'j'</span>, <span class="hljs-string">".---"</span>),
        (<span class="hljs-string">'k'</span>, <span class="hljs-string">"-.-"</span>),
        (<span class="hljs-string">'l'</span>, <span class="hljs-string">".-.."</span>),
        (<span class="hljs-string">'m'</span>, <span class="hljs-string">"--"</span>),
        (<span class="hljs-string">'n'</span>, <span class="hljs-string">"-."</span>),
        (<span class="hljs-string">'o'</span>, <span class="hljs-string">"---"</span>),
        (<span class="hljs-string">'p'</span>, <span class="hljs-string">".--."</span>),
        (<span class="hljs-string">'q'</span>, <span class="hljs-string">"--.-"</span>),
        (<span class="hljs-string">'r'</span>, <span class="hljs-string">".-."</span>),
        (<span class="hljs-string">'s'</span>, <span class="hljs-string">"..."</span>),
        (<span class="hljs-string">'t'</span>, <span class="hljs-string">"-"</span>),
        (<span class="hljs-string">'u'</span>, <span class="hljs-string">"..-"</span>),
        (<span class="hljs-string">'v'</span>, <span class="hljs-string">"...-"</span>),
        (<span class="hljs-string">'w'</span>, <span class="hljs-string">".--"</span>),
        (<span class="hljs-string">'x'</span>, <span class="hljs-string">"-..-"</span>),
        (<span class="hljs-string">'y'</span>, <span class="hljs-string">"-.--"</span>),
        (<span class="hljs-string">'z'</span>, <span class="hljs-string">"--.."</span>),
        (<span class="hljs-string">'1'</span>, <span class="hljs-string">".----"</span>),
        (<span class="hljs-string">'2'</span>, <span class="hljs-string">"..---"</span>),
        (<span class="hljs-string">'3'</span>, <span class="hljs-string">"...--"</span>),
        (<span class="hljs-string">'4'</span>, <span class="hljs-string">"....-"</span>),
        (<span class="hljs-string">'5'</span>, <span class="hljs-string">"....."</span>),
        (<span class="hljs-string">'6'</span>, <span class="hljs-string">"-...."</span>),
        (<span class="hljs-string">'7'</span>, <span class="hljs-string">"--..."</span>),
        (<span class="hljs-string">'8'</span>, <span class="hljs-string">"---.."</span>),
        (<span class="hljs-string">'9'</span>, <span class="hljs-string">"----."</span>),
        (<span class="hljs-string">'0'</span>, <span class="hljs-string">"-----"</span>),
        (<span class="hljs-string">'.'</span>, <span class="hljs-string">".-.-.-"</span>),
        (<span class="hljs-string">','</span>, <span class="hljs-string">"--..--"</span>),
        (<span class="hljs-string">'?'</span>, <span class="hljs-string">"..--.."</span>),
        (<span class="hljs-string">'\''</span>, <span class="hljs-string">".----."</span>),
        (<span class="hljs-string">'!'</span>, <span class="hljs-string">"-.-.--"</span>),
        (<span class="hljs-string">'/'</span>, <span class="hljs-string">"-..-."</span>),
        (<span class="hljs-string">'('</span>, <span class="hljs-string">"-.--."</span>),
        (<span class="hljs-string">')'</span>, <span class="hljs-string">"-.--.-"</span>),
        (<span class="hljs-string">'&amp;'</span>, <span class="hljs-string">".-..."</span>),
        (<span class="hljs-string">':'</span>, <span class="hljs-string">"---..."</span>),
        (<span class="hljs-string">';'</span>, <span class="hljs-string">"-.-.-."</span>),
        (<span class="hljs-string">'='</span>, <span class="hljs-string">"-...-"</span>),
        (<span class="hljs-string">'+'</span>, <span class="hljs-string">".-.-."</span>),
        (<span class="hljs-string">'-'</span>, <span class="hljs-string">"-....-"</span>),
        (<span class="hljs-string">'_'</span>, <span class="hljs-string">"..--.-"</span>),
        (<span class="hljs-string">'"'</span>, <span class="hljs-string">".-..-."</span>),
        (<span class="hljs-string">'$'</span>, <span class="hljs-string">"...-..-"</span>),
        (<span class="hljs-string">'@'</span>, <span class="hljs-string">".--.-."</span>),
        (<span class="hljs-string">' '</span>, <span class="hljs-string">" "</span>),
    ].iter().cloned().collect();

    <span class="hljs-comment">// Read standard input per line</span>
    <span class="hljs-keyword">for</span> line_res <span class="hljs-keyword">in</span> io::stdin().lock().lines() {
        <span class="hljs-keyword">let</span> line = line_res?;
        <span class="hljs-keyword">if</span> line == <span class="hljs-string">"quit()"</span> {
            <span class="hljs-keyword">break</span>;
        }
        <span class="hljs-comment">// Turn line into morse code</span>
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> morse = <span class="hljs-built_in">String</span>::new();
        <span class="hljs-keyword">for</span> c <span class="hljs-keyword">in</span> line.chars() {
            <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Some</span>(morse_code_char) = morse_code_alphabet.get(&amp;c) {
                morse.push_str(morse_code_char);
                <span class="hljs-comment">// Separate characters with a comma</span>
                morse.push_str(<span class="hljs-string">","</span>);
            }
        }
        <span class="hljs-comment">// Blink LED based on characters</span>
        <span class="hljs-keyword">for</span> c <span class="hljs-keyword">in</span> morse.chars() {
            <span class="hljs-keyword">match</span> c {
                <span class="hljs-string">'.'</span> =&gt; {
                    led.on();
                    sleep(Duration::from_millis(DOT_DELAY));
                    led.off();
                    sleep(Duration::from_millis(PUSH_DELAY));
                },
                <span class="hljs-string">'-'</span> =&gt; {
                    led.on();
                    sleep(Duration::from_millis(DASH_DELAY));
                    led.off();
                    sleep(Duration::from_millis(PUSH_DELAY));
                },
                <span class="hljs-string">','</span> =&gt; {
                    sleep(Duration::from_millis(LETTER_DELAY));
                },
                <span class="hljs-string">' '</span> =&gt; {
                    sleep(Duration::from_millis(WORD_DELAY));
                },
                _ =&gt; {
                    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Unknown character: {}"</span>, c);
                    <span class="hljs-keyword">break</span>;
                }
            }
        }
        sleep(Duration::from_millis(WORD_DELAY));
    }

    <span class="hljs-comment">// Free the variable and associated resources</span>
    led.close();

    <span class="hljs-literal">Ok</span>(())
}
</code></pre>
<h2 id="heading-appendix">Appendix</h2>
<h3 id="heading-targets">Targets</h3>
<p>In Rust, the <em>target</em> is the platform (architecture) the program is compiled for. Cargo automatically detects the target, based on the file system layout <sup>[<a target="_blank" href="https://doc.rust-lang.org/cargo/reference/cargo-targets.html#target-auto-discovery">2</a>]</sup>.</p>
<p>You can see the list of built-in targets, by running:</p>
<pre><code class="lang-bash">rustc --<span class="hljs-built_in">print</span> target-list
<span class="hljs-comment"># OR</span>
rustup target list
</code></pre>
<p>From here you can add a new target to your project, by running:</p>
<pre><code class="lang-bash">rustup target add &lt;target&gt;
</code></pre>
<p>The given target is often in the form of a <em>triple</em> <sup>[<a target="_blank" href="https://rust-lang.github.io/rfcs/0131-target-specification.html">3</a>]</sup>:</p>
<ul>
<li>The architecture</li>
<li>The vendor</li>
<li>The operating system type</li>
<li>The environment type</li>
</ul>
<p><em>This is refered to as a 'target triple', because the fourth part is optional.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Solve Project Euler Problems in Rust ]]>
                </title>
                <description>
                    <![CDATA[ You can now solve the classic Project Euler programming problems using the Rust language. Each of these problems comes with a user-friendly test suite.  Here's the full Project Euler Rust GitHub repository. If you do not know Rust, and want to learn ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/project-euler-problems-in-rust/</link>
                <guid isPermaLink="false">66ace42ccadcaa37c68b50a6</guid>
                
                    <category>
                        <![CDATA[ freeCodeCamp.org ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Rust ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Shaun Hamilton ]]>
                </dc:creator>
                <pubDate>Thu, 03 Mar 2022 17:09:14 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/02/euler-rust-local-ext-9-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You can now solve the classic Project Euler programming problems using the Rust language. Each of these problems comes with a user-friendly test suite. </p>
<p>Here's the full <a target="_blank" href="https://github.com/freeCodeCamp/euler-rust">Project Euler Rust GitHub repository</a>.</p>
<p>If you do not know Rust, and want to learn it, you can start with <a target="_blank" href="https://www.freecodecamp.org/news/rust-in-replit/">freeCodeCamp's interactive Rust course</a>.</p>
<p>All right. Let's see how to get started working through Project Euler in Rust.</p>
<h2 id="heading-how-to-run-the-project-euler-problems-locally-in-vscode">How to Run the Project Euler Problems Locally in VSCode</h2>
<p>First, you'll need to download and install the <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=freeCodeCamp.freecodecamp-courses">freeCodeCamp Courses VSCode extension</a>.</p>
<p>Also, ensure you have the Microsoft <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers">Dev Containers VSCode extension</a>.</p>
<p>Then, in an empty workspace, open the VSCode command palette with <code>Ctrl/Cmd + Shift + P</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/euler-rust-local-ext-1.png" alt="euler-rust-local-ext-1" width="600" height="400" loading="lazy"></p>
<p>Select the command <code>freeCodeCamp: Open Course</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/euler-rust-local-ext-2.png" alt="euler-rust-local-ext-2" width="600" height="400" loading="lazy"></p>
<p>Next, choose the <code>Project Euler: Rust</code> option.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/euler-rust-local-ext-3.png" alt="euler-rust-local-ext-3" width="600" height="400" loading="lazy"></p>
<p>Once the course is cloned, open the command palette again and select <code>Dev Containers: Rebuild and Reopen in Container</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/euler-rust-local-ext-4.png" alt="euler-rust-local-ext-4" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/euler-rust-local-ext-5.png" alt="euler-rust-local-ext-5" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/euler-rust-local-ext-6.png" alt="euler-rust-local-ext-6" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/euler-rust-gitpod.png" alt="euler-rust-gitpod" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-run-the-project-euler-problems-locally-without-the-extension">How to Run the Project Euler Problems Locally without the Extension</h2>
<p>If you would prefer to run these without the VS Code extension, you'll need to fork the repository:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/euler-rust-fork.png" alt="euler-rust-fork" width="600" height="400" loading="lazy"></p>
<p>Then clone your fork to your local machine.</p>
<pre><code class="lang-bash">git <span class="hljs-built_in">clone</span> https://github.com/&lt;your_username&gt;/euler-rust.git
<span class="hljs-built_in">cd</span> euler-rust
</code></pre>
<p>Build and open the Docker container like this:</p>
<pre><code class="lang-bash">docker build -f Dockerfile -t euler-rust .
</code></pre>
<p>And then start the course:</p>
<pre><code class="lang-bash">npm i &amp;&amp; npm run start
</code></pre>
<p>Optionally, you can also clone and build the container with Docker like this:</p>
<pre><code class="lang-bash">docker build github.com/&lt;your_username&gt;/euler-rust
</code></pre>
<h2 id="heading-how-to-run-the-project-euler-problems-using-gitpod">How to Run the Project Euler Problems Using Gitpod</h2>
<p>GitPod is a popular tool for running a VM in your browser, and is yet another way you can solve these Project Euler problems. First, fork the repository:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/euler-rust-fork.png" alt="euler-rust-fork" width="600" height="400" loading="lazy"></p>
<p>Then open your fork in Gitpod: <code>https://gitpod.io/#https://github.com/&lt;your_user_name&gt;/euler-rust</code></p>
<p>Optionally, if you have the Gitpod browser extension installed, you can click the <code>Gitpod</code> button it adds to GitHub:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/euler-rust-gitpod-button.png" alt="euler-rust-gitpod-button" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/02/euler-rust-gitpod-setup.png" alt="euler-rust-gitpod-setup" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/euler-rust-gitpod.png" alt="euler-rust-gitpod" width="600" height="400" loading="lazy"></p>
<h2 id="heading-useful-information">Useful Information</h2>
<p><em>NOTE:</em> If you are using any of the above methods with Docker, you will need to have Docker installed on your machine, and have the Daemon running.</p>
<p>You should need to only edit the <code>src/lib.rs</code> file within each <code>project-euler-problems-...</code> directory, and you can follow the example code there to get started.</p>
<p>To compile your code, before running the tests, run:</p>
<pre><code class="lang-bash">wasm-pack build
</code></pre>
<p>If at any point you get stuck, I recommend that you check out more information about <a target="_blank" href="https://www.rust-lang.org/what/wasm">Rust with WASM</a>. Otherwise, feel free to open a new topic on the <a target="_blank" href="https://forum.freecodecamp.org/">freeCodeCamp forum</a>.</p>
<h2 id="heading-how-the-project-works">How the Project Works</h2>
<p>First, taking your Rust code in <code>src/lib.rs</code>:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> wasm_bindgen::prelude::*;

<span class="hljs-comment">// Example format to write functions:</span>
<span class="hljs-meta">#[wasm_bindgen(js_name = camelCaseName)]</span> <span class="hljs-comment">// js_name must equal function name tested on client</span>
<span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">snake_case_name</span></span>(num: <span class="hljs-built_in">i32</span>) -&gt; <span class="hljs-built_in">i32</span> { <span class="hljs-comment">// Function must be public</span>
    <span class="hljs-comment">// All numbers in JS are 32-bit</span>
    num
}
</code></pre>
<p>The Rust is transpiled into JavaScript code using <code>wasm-pack</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> wasm <span class="hljs-keyword">from</span> <span class="hljs-string">"./curriculum_bg.wasm"</span>;

<span class="hljs-comment">/**
 * @param {number} n
 * @returns {number}
 */</span>
<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">camelCaseName</span>(<span class="hljs-params">num</span>) </span>{
  <span class="hljs-keyword">var</span> ret = wasm.camelCaseName(num);
  <span class="hljs-keyword">return</span> ret;
}
</code></pre>
<h2 id="heading-frequently-asked-questions-faq">Frequently Asked Questions (FAQ)</h2>
<blockquote>
<p>Will these Project Euler problems be made available in other programming languages?</p>
</blockquote>
<p>We welcome any and all well-intended contributions to the freeCodeCamp community. So, if you are interested in developing on a fork of the repository, please do so!</p>
<blockquote>
<p>Can I save my progress on my freeCodeCamp.org account?</p>
</blockquote>
<p>Not yet, but it is something that we can look into further.</p>
<blockquote>
<p>The Docker step takes such a long time. Is there a quicker way to get started?</p>
</blockquote>
<p>Well, provided you have the tenacity to install all the necessary tooling on your local machine, you can simple run the following commands within the project:</p>
<pre><code class="lang-bash">npm ci
npm run start
</code></pre>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> project-euler-problems-1-to-100
wasm-pack build
</code></pre>
<p>Now, you should be able to open a browser and navigate to <code>http://localhost:8080/</code>, and begin.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn Rust Programming Course – Interactive Rust Language Tutorial on Replit ]]>
                </title>
                <description>
                    <![CDATA[ For six years in a row, Rust has been voted the most loved programming language by Stack Overflow. So if you're ready to learn this popular programming language, this course will introduce you to Rust so you can start using it in your projects. You w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/rust-in-replit/</link>
                <guid isPermaLink="false">66ace42fcadcaa37c68b50a8</guid>
                
                    <category>
                        <![CDATA[ repl.it ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Rust ]]>
                    </category>
                
                    <category>
                        <![CDATA[ RustLang ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Shaun Hamilton ]]>
                </dc:creator>
                <pubDate>Tue, 30 Nov 2021 14:35:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/11/rust-and-sunset.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>For six years in a row, Rust has been voted the most loved programming language by <a target="_blank" href="https://insights.stackoverflow.com/survey/2021#technology-most-loved-dreaded-and-wanted">Stack Overflow</a>.</p>
<p>So if you're ready to learn this popular programming language, this course will introduce you to Rust so you can start using it in your projects.</p>
<p>You will be working entirely within your browser by using the <a target="_blank" href="https://replit.com">Replit</a> interactive programming environment. freeCodeCamp has partnered with Replit who has made this course possible.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/MsocPEZBd-M" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>There is also a video version of this course on the <a target="_blank" href="https://youtu.be/MsocPEZBd-M">freeCodeCamp YouTube channel</a>.</p>
<p>To get the most out of this course, you should have intermediate knowledge of at least one other programming language. If you are new to programming, you should try out <a target="_blank" href="https://www.freecodecamp.org/learn/">freeCodeCamp's interactive curriculum</a> and then come back to this course.</p>
<p>To help you learn Rust, we will create two projects:</p>
<ol>
<li>A calculator for the command line</li>
<li>A command line tool which takes two images and combines their pixels</li>
</ol>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<p>Here are the sections and topics we'll cover in this course. You can click through the table of contents below to jump to particular parts, or you can just go through from start to finish.</p>
<ul>
<li><a class="post-section-overview" href="#heading-rust-overview">Rust Overview</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-rust-in-replit">How to Use Rust in Replit</a></li>
<li><a class="post-section-overview" href="#heading-basics-of-rust">Basics of Rust</a><ul>
<li><a class="post-section-overview" href="#heading-variables-in-rust">Variables in Rust</a></li>
<li><a class="post-section-overview" href="#heading-functions-in-rust">Functions in Rust</a></li>
<li><a class="post-section-overview" href="#heading-strings-and-slices-in-rust-1">Strings and Slices in Rust</a></li>
<li><a class="post-section-overview" href="#heading-the-char-type-in-rust">The <code>char</code> Type in Rust</a></li>
<li><a class="post-section-overview" href="#heading-number-types-in-rust">Number Types in Rust</a></li>
<li><a class="post-section-overview" href="#heading-structs-in-rust">Structs in Rust</a></li>
<li><a class="post-section-overview" href="#heading-enums-in-rust">Enums in Rust</a></li>
<li><a class="post-section-overview" href="#heading-macros-in-rust">Macros in Rust</a></li>
<li><a class="post-section-overview" href="#heading-ownership-in-rust">Ownership in Rust</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-project-1-build-a-cli-calculator-in-rust">Project #1 - Build a CLI Calculator in Rust</a><ul>
<li><a class="post-section-overview" href="#heading-project-outcome">Project Outcome</a></li>
<li><a class="post-section-overview" href="#heading-cli-calculator-project-methodology">CLI Calculator Project Methodology</a><ul>
<li><a class="post-section-overview" href="#heading-step-1-create-a-new-project">Step 1 - Create a New Project</a></li>
<li><a class="post-section-overview" href="#heading-step-2-understand-the-syntax">Step 2 - Understand the Syntax</a></li>
<li><a class="post-section-overview" href="#heading-step-3-run-the-project">Step 3 - Run the Project</a></li>
<li><a class="post-section-overview" href="#heading-step-4-command-line-arguments">Step 4 - Command Line Arguments</a></li>
<li><a class="post-section-overview" href="#heading-step-5-parse-strings-into-numbers">Step 5 - Parse Strings into Numbers</a></li>
<li><a class="post-section-overview" href="#heading-step-6-perform-basic-arithmetic-operations">Step 6 - Perform Basic Arithmetic Operations</a></li>
<li><a class="post-section-overview" href="#heading-step-7-format-the-output">Step 7 - Format the Output</a></li>
<li><a class="post-section-overview" href="#heading-step-8-bring-it-all-together">Step 8 - Bring It All Together</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-project-2-build-an-image-combiner-in-rust">Project #2 - Build an Image Combiner in Rust</a><ul>
<li><a class="post-section-overview" href="#heading-project-outcome-1">Project Outcome</a></li>
<li><a class="post-section-overview" href="#heading-image-combiner-project-methodology">Image Combiner Project Methodology</a><ul>
<li><a class="post-section-overview" href="#heading-step-1-create-a-new-project-1">Step 1 - Create a New Project</a></li>
<li><a class="post-section-overview" href="#heading-step-2-add-a-new-module-for-args">Step 2 - Add a New Module for Args</a></li>
<li><a class="post-section-overview" href="#heading-step-3-import-and-use-the-args-module">Step 3 - Import and Use the <code>args</code> Module</a></li>
<li><a class="post-section-overview" href="#heading-step-4-add-an-external-crate">Step 4 - Add an External Crate</a></li>
<li><a class="post-section-overview" href="#heading-step-5-read-an-image-file">Step 5 - Read an Image File</a></li>
<li><a class="post-section-overview" href="#heading-step-6-handle-errors-with-result">Step 6 - Handle Errors with <code>Result</code></a></li>
<li><a class="post-section-overview" href="#heading-step-7-resize-the-images-to-match">Step 7 - Resize the Images to Match</a></li>
<li><a class="post-section-overview" href="#heading-step-8-create-a-floating-image">Step 8 - Create a Floating Image</a></li>
<li><a class="post-section-overview" href="#heading-step-9-create-the-combined-image-data">Step 9 - Create the Combined Image Data</a></li>
<li><a class="post-section-overview" href="#heading-step-10-attach-the-combined-data-to-the-floating-image">Step 10 - Attach the Combined Data to the Floating Image</a></li>
<li><a class="post-section-overview" href="#heading-step-11-write-the-image-to-a-file">Step 11 - Write the Image to a File</a></li>
<li><a class="post-section-overview" href="#heading-step-12-bring-it-all-together">Step 12 - Bring It All Together</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-rust-overview">Rust Overview</h2>
<p>Rust is a <em>systems-level</em> programming language.</p>
<blockquote>
<p>"[Rust] deals with low-level details of memory management, data representation, and concurrency."  </p>
<p>"... the language is designed to guide you naturally towards reliable code that is efficient in terms of speed and memory usage." (<a target="_blank" href="https://doc.rust-lang.org/book/foreword.html">Source: Rust docs</a>)</p>
</blockquote>
<p>The main tooling within the Rust ecosystem is:</p>
<ul>
<li>rustc – The compiler which takes your Rust code and compiles it into binary (machine readable code)</li>
<li>rustup – The command line utility to install and update Rust</li>
<li>cargo – The Rust build system and package manager</li>
</ul>
<h2 id="heading-how-to-use-rust-in-replit">How to Use Rust in Replit</h2>
<p>For this course, you will be using <a target="_blank" href="https://github.com/freeCodeCamp/Rust-In-Replit/">this GitHub repository</a> as a boilerplate.</p>
<p>To begin, click the following link to create a new REPL from the boilerplate:</p>
<p><a href="https://replit.com/github/freeCodeCamp/Rust-in-Replit">
  <img src="https://replit.com/badge/github/freeCodeCamp/Rust-in-Replit" alt="run on replit" width="131" height="36" loading="lazy">
</a></p>
<p>Then in the Import from GitHub modal, open the Language dropdown and select Bash:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/select-bash-as-language.jpg" alt="The Import from GitHub modal on Replit showing the Language dropdown and selecting Bash as the language." width="600" height="400" loading="lazy"></p>
<p>Then click the Import from GitHub button in the lower right to import the boilerplate code into Replit.</p>
<p>Finally, to start the course, click the Run button at the top of the screen and follow the instructions in the console on the right:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/run-the-course-and-select-a-language.jpg" alt="The beginning of the course after clicking the Run button, with a README with instructions on the left and the Replit console on the right with a welcome message." width="600" height="400" loading="lazy"></p>
<h2 id="heading-basics-of-rust">Basics of Rust</h2>
<h3 id="heading-variables-in-rust">Variables in Rust</h3>
<p>You can declare variables using the <code>let</code>, <code>const</code>, or <code>static</code> keywords:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> my_variable = <span class="hljs-number">0</span>;
<span class="hljs-keyword">const</span> MY_CONSTANT: <span class="hljs-built_in">u8</span> = <span class="hljs-number">0</span>;
<span class="hljs-keyword">static</span> MY_STATIC: <span class="hljs-built_in">u8</span> = <span class="hljs-number">0</span>;
</code></pre>
<p>By default, all variables are immutable. You can make a variable mutable by using the <code>mut</code> keyword:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> my_mutable_variable = <span class="hljs-number">0</span>;
</code></pre>
<p>Rust convention relies on the following casing conventions:</p>
<table>
<thead>
<tr>
<th>Object</th>
<th>Casing</th>
</tr>
</thead>
<tbody>
<tr>
<td>Variables</td>
<td>snake_case</td>
</tr>
<tr>
<td>Functions</td>
<td>snake_case</td>
</tr>
<tr>
<td>Files</td>
<td>snake_case</td>
</tr>
<tr>
<td>Constants</td>
<td>SCREAMING_SNAKE_CASE</td>
</tr>
<tr>
<td>Statics</td>
<td>SCREAMING_SNAKE_CASE</td>
</tr>
<tr>
<td>Types</td>
<td>PascalCase</td>
</tr>
<tr>
<td>Traits</td>
<td>PascalCase</td>
</tr>
<tr>
<td>Enums</td>
<td>PascalCase</td>
</tr>
</tbody>
</table>

<p>Since Rust is statically typed, you'll need to explicitly type variables – unless the variable is declared with <code>let</code> and the type can be inferred.</p>
<h3 id="heading-functions-in-rust">Functions in Rust</h3>
<p>You declare functions using the <code>fn</code> keyword:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
  <span class="hljs-comment">// This is a code comment</span>
}
</code></pre>
<p>Functions return using the <code>return</code> keyword, and you need to explicitly specify the return type of a function, unless the return type is an empty tuple <code>()</code>:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() -&gt; () { <span class="hljs-comment">// Unnecessary return type</span>
  my_func();
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">my_func</span></span>() -&gt; <span class="hljs-built_in">u8</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Functions also return an expression missing the semi-colon:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">my_func</span></span>() -&gt; <span class="hljs-built_in">u8</span> {
  <span class="hljs-number">0</span>
}
</code></pre>
<p>Function parameters are typed using the <code>:</code> syntax:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
  <span class="hljs-keyword">let</span> _unused_variable = my_func(<span class="hljs-number">10</span>);
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">my_func</span></span>(x: <span class="hljs-built_in">u8</span>) -&gt; <span class="hljs-built_in">i32</span> {
  x <span class="hljs-keyword">as</span> <span class="hljs-built_in">i32</span>
}
</code></pre>
<p>The underscore before a variable name is a convention to indicate that the variable is unused. The <code>as</code> keyword asserts the type of the expression, provided the type conversion is valid.</p>
<h3 id="heading-strings-and-slices-in-rust">Strings and Slices in Rust</h3>
<p>A common point of confusion for beginner <em>Rustacians</em> is the difference between the <code>String</code> struct and the <code>str</code> type.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> my_str: &amp;<span class="hljs-built_in">str</span> = <span class="hljs-string">"Hello, world!"</span>;

<span class="hljs-keyword">let</span> my_string: <span class="hljs-built_in">String</span> = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Hello, world!"</span>);
</code></pre>
<p>In the above example, <code>my_str</code> is a reference to a <em>string literal</em>, and <code>my_string</code> is an instance of the <code>String</code> struct. </p>
<p>An important distinction between the two is that <code>my_str</code> is stack stored, and <code>my_string</code> is heap allocated. This means <code>my_str</code>'s value cannot change, and its size is fixed, whilst <code>my_string</code> can have an unknown size at compile time.</p>
<p>The <em>string literal</em> is also known as a <em>string slice</em>. This is because a <code>&amp;str</code> refers to part of a string. Generally, this is how arrays and strings are similar:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> my_string = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"The quick brown fox"</span>);
<span class="hljs-keyword">let</span> my_str: &amp;<span class="hljs-built_in">str</span> = &amp;my_string[<span class="hljs-number">4</span>..<span class="hljs-number">9</span>]; <span class="hljs-comment">// "quick"</span>

<span class="hljs-keyword">let</span> my_arr: [<span class="hljs-built_in">usize</span>; <span class="hljs-number">5</span>] = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">let</span> my_arr_slice: &amp;[<span class="hljs-built_in">usize</span>] = &amp;my_arr[<span class="hljs-number">0</span>..<span class="hljs-number">3</span>]; <span class="hljs-comment">// [1, 2, 3]</span>
</code></pre>
<p>The <code>[T; n]</code> notation is used to create an array of <code>n</code> elements of type <code>T</code>.</p>
<h3 id="heading-the-char-type-in-rust">The <code>char</code> Type in Rust</h3>
<p>A <code>char</code> is a USV (Unicode Scalar Value), which is represented in unicode with values like <code>U+221E</code> – the unicode for '∞'. You can think of a collection or array of <code>char</code>s as a string:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> my_str: &amp;<span class="hljs-built_in">str</span> = <span class="hljs-string">"Hello, world!"</span>;

<span class="hljs-keyword">let</span> collection_of_chars: &amp;<span class="hljs-built_in">str</span> = my_str.chars().as_str();
</code></pre>
<h3 id="heading-number-types-in-rust">Number Types in Rust</h3>
<p>There are many types of numbers in Rust:</p>
<ul>
<li>Unsigned Integers: <code>u8</code>, <code>u16</code>, <code>u32</code>, <code>u64</code>, <code>u128</code></li>
<li>Signed Integers: <code>i8</code>, <code>i16</code>, <code>i32</code>, <code>i64</code>, <code>i128</code></li>
<li>Floating Point Numbers: <code>f32</code>, <code>f64</code></li>
</ul>
<p>Unsigned integers only represent positive whole numbers.</p>
<p>Signed integers represent both positive and negative whole numbers.</p>
<p>And floats only represent positive and negative fractions.</p>
<h3 id="heading-structs-in-rust">Structs in Rust</h3>
<p>A <em>struct</em> is a custom data type used to group related data. You have already come across a struct in the <a class="post-section-overview" href="#heading-strings-and-slices-in-rust-1">Strings and Slices</a> section:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">String</span></span> {
  vec: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt;,
}
</code></pre>
<p>The <code>String</code> struct consists of a <code>vec</code> field, which is a <code>Vec</code> of <code>u8</code>s. The <code>Vec</code> is a dynamically-sized array.</p>
<p>An instance of a struct is then declared by giving values to the fields:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MyStruct</span></span> {
  field_1: <span class="hljs-built_in">u8</span>,
}

<span class="hljs-keyword">let</span> my_struct = MyStruct { field_1: <span class="hljs-number">0</span>, };
</code></pre>
<p>Previously, the <code>String</code> struct was used with its <code>from</code> function to create a <code>String</code> from a <code>&amp;str</code>. This is possible, because the <code>from</code> function is implemented for <code>String</code>:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> <span class="hljs-built_in">String</span> {
  <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">from</span></span>(s: &amp;<span class="hljs-built_in">str</span>) -&gt; <span class="hljs-keyword">Self</span> {
    <span class="hljs-built_in">String</span> {
      vec: <span class="hljs-built_in">Vec</span>::from(s.as_bytes()),
    }
  }
}
</code></pre>
<p>You use the <code>Self</code> keyword in place of the type of the struct.</p>
<p>Structs can also take other variants:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MyUnitStruct</span></span>;
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MyTupleStruct</span></span>(<span class="hljs-built_in">u8</span>, <span class="hljs-built_in">u8</span>);
</code></pre>
<h3 id="heading-enums-in-rust">Enums in Rust</h3>
<p>Similar to other languages, enums are useful for acting as types and as values.</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">MyErrors</span></span> {
  BrainTooTired,
  TimeOfDay(<span class="hljs-built_in">String</span>)
  CoffeeCupEmpty,
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">work</span></span>() -&gt; <span class="hljs-built_in">Result</span>&lt;(), MyErrors&gt; { <span class="hljs-comment">// Result is also an enum</span>
  <span class="hljs-keyword">if</span> state == <span class="hljs-string">"missing semi-colon"</span> {
    <span class="hljs-literal">Err</span>(MyErrors::BrainTooTired)
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> state == <span class="hljs-string">"06:00"</span> {
    <span class="hljs-literal">Err</span>(MyErrors::TImeOfDay(<span class="hljs-string">"It's too early to work"</span>.to_string()))
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> state == <span class="hljs-string">"22:00"</span> {
    <span class="hljs-literal">Err</span>(MyErrors::TimeOfDay(<span class="hljs-string">"It's too late to work"</span>.to_string()))
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> state == <span class="hljs-string">"empty"</span> {
    <span class="hljs-literal">Err</span>(MyErrors::CoffeeCupEmpty)
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-literal">Ok</span>(())
  }
}
</code></pre>
<h3 id="heading-macros-in-rust">Macros in Rust</h3>
<p>A macro is similar to a function, but you can think of it as a piece of code which writes other code. For now, the main differences between a function and a macro to keep in mind are:</p>
<ul>
<li>Macros are called using a bang (<code>!</code>)</li>
<li>Macros can take a variable number of arguments, while functions in Rust cannot</li>
</ul>
<p>One of the most common macros is the <code>println!</code> macro, which prints to the console:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> my_str = <span class="hljs-string">"Hello, world!"</span>;
<span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, my_str);
</code></pre>
<p>You use the <code>{}</code> syntax to insert a variable into a string.</p>
<p>Another common macro is <code>panic!</code>. <em>Panicking</em> is Rust's way of 'erroring out'. It is wise to think of a panic in Rust as a poorly-handled error. The macro accepts a string literal, and panics with that message.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> am_i_an_error = <span class="hljs-literal">true</span>;

<span class="hljs-keyword">if</span> (am_i_an_error) {
  <span class="hljs-built_in">panic!</span>(<span class="hljs-string">"There was an error"</span>);
}
</code></pre>
<pre><code class="lang-bash">$ cargo run
   Compiling fcc-rust-in-replit v0.1.0 (/home/runner/Rust-in-Replit)
    Finished dev [unoptimized + debuginfo] target(s) <span class="hljs-keyword">in</span> 1.66s
     Running `target/debug/calculator`
thread <span class="hljs-string">'main'</span> panicked at <span class="hljs-string">'There was an error'</span>, src/main.rs
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
</code></pre>
<h3 id="heading-ownership-in-rust">Ownership in Rust</h3>
<p>An important concept in Rust is <em>ownership</em>. There are three main ownership rules:</p>
<ul>
<li>Each value in Rust has a variable that's called its <em>owner</em>.</li>
<li>There can only be one owner at a time.</li>
<li>When the owner goes out of scope, the value will be dropped.<br>(<a target="_blank" href="https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html?highlight=heap#ownership-rules">Source: The Rust Book</a>)</li>
</ul>
<p>This is how Rust gets away with not having a typical garbage collector, whilst also not requiring the programmer to explicitly manage memory. Here is an example of ownership:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() { <span class="hljs-comment">// first_string is not declared yet -&gt; has no value</span>
  <span class="hljs-keyword">let</span> first_string = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"freeCodeCamp"</span>); <span class="hljs-comment">// first_string is now owner of the value "freeCodeCamp"</span>
  <span class="hljs-keyword">let</span> second_string = first_string; <span class="hljs-comment">// second_string takes ownership of the value "freeCodeCamp"</span>

  <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Hello, {}!"</span>, first_string); <span class="hljs-comment">// first_string is NOT valid, because the value was moved to second_string</span>
}
</code></pre>
<p>As the <code>println!</code> macro tries to refer to an invalid variable, this code does not compile. To fix this, instead of moving the value of <code>first_string</code> into <code>second_string</code>, <code>second_string</code> can be assigned a reference to <code>first_string</code>:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
  <span class="hljs-keyword">let</span> first_string: <span class="hljs-built_in">String</span> = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"freeCodeCamp"</span>);
  <span class="hljs-keyword">let</span> second_string: &amp;<span class="hljs-built_in">String</span> = &amp;first_string; <span class="hljs-comment">// first_string is still the owner of the value "freeCodeCamp"</span>

  <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Hello, {}!"</span>, first_string);
}
</code></pre>
<p>The ampersand (<code>&amp;</code>) indicates that the value is a reference. That is, <code>second_string</code> no longer takes ownership of <code>"freeCodeCamp"</code>, but, instead, points to the same point in memory as <code>first_string</code>.</p>
<h2 id="heading-project-1-build-a-cli-calculator-in-rust">Project #1 – Build a CLI Calculator in Rust</h2>
<h3 id="heading-project-outcome">Project Outcome</h3>
<p>At the end of this project, you will be able to perform basic arithmetic operations on numbers using the command line.</p>
<p>Examples of expected input and output look like this:</p>
<pre><code class="lang-bash">$ calculator 1 + 1
$ 1 + 1 = 2

$ calculator 138 / 4
$ 138 / 4 = 34.5
</code></pre>
<h3 id="heading-cli-calculator-project-methodology">CLI Calculator Project Methodology</h3>
<h4 id="heading-step-1-create-a-new-project">Step 1 – Create a New Project</h4>
<p>Use Cargo to create a new project named <code>calculator</code>:</p>
<pre><code class="lang-bash">$ cargo new calculator
</code></pre>
<p>This creates a new directory named <code>calculator</code>, initialises it as a Git repository, and adds useful boilerplate for your project.</p>
<p>The boilerplate includes:</p>
<ul>
<li><code>Cargo.toml</code> – The manifest file used by Cargo to manage your project's metadata</li>
<li><code>src/</code> – The directory where your project code should live</li>
<li><code>src/main.rs</code> – The default file Cargo uses as your application entrypoint</li>
</ul>
<h4 id="heading-step-2-understand-the-syntax">Step 2 – Understand the Syntax</h4>
<p>The <code>calculator/Cargo.toml</code> file contains the following:</p>
<pre><code class="lang-toml"><span class="hljs-section">[package]</span>
<span class="hljs-attr">name</span> = <span class="hljs-string">"calculator"</span>
<span class="hljs-attr">version</span> = <span class="hljs-string">"0.1.0"</span>
<span class="hljs-attr">edition</span> = <span class="hljs-string">"2018"</span>

<span class="hljs-comment"># See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html</span>

<span class="hljs-section">[dependencies]</span>
</code></pre>
<p>The <code>[package]</code> denotes your project's metadata.</p>
<p>The <code>[dependencies]</code> heading denotes the crates your project depends on. <em>Crates are like external libraries.</em></p>
<p>The <code>calculator/src/main.rs</code> file contains the following:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
  <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Hello, world!"</span>);
}
</code></pre>
<p>This file contains a function declaration with the handle <code>main</code>. By default, rustc calls the <code>main</code> function first whenever the executable is run.</p>
<p><code>println!</code> is a built-in macro which prints to the console.</p>
<h4 id="heading-step-3-run-the-project">Step 3 – Run the Project</h4>
<p>You can either use Cargo to run your project code:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Within the calculator/ directory</span>
$ cargo run
   Compiling fcc-rust-in-replit v0.1.0 (/home/runner/Rust-in-Replit-1)
    Finished dev [unoptimized + debuginfo] target(s) <span class="hljs-keyword">in</span> 0.80s
     Running `target/debug/calculator`
Hello, world!
</code></pre>
<p>Or, you can use rustc to compile your project, then you can run the binary:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Within the calculator/ directory</span>
$ rustc src/main.rs
$ ./main
Hello, world!
</code></pre>
<h4 id="heading-step-4-command-line-arguments">Step 4 – Command Line Arguments</h4>
<p>The Rust standard library comes with an <code>env</code> module, which allows access to the command line arguments passed when calling the program.</p>
<p>The necessary exports from the <code>env</code> module are the <code>args</code> function, and the <code>Args</code> struct. The <code>args</code> function returns an instance of the <code>Args</code> struct, and is imported into the file scope with:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::env::{args, Args};
</code></pre>
<p>To get an idea of what the <code>Args</code> struct looks like, the <code>args</code> variable is printed to the console:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
  <span class="hljs-keyword">let</span> args: Args = args();
  <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, args);
}
</code></pre>
<pre><code class="lang-bash">$ cargo run -- fCC
   Compiling calculator v0.1.0 (/home/runner/Rust-in-Replit/calculator)
    Finished dev [unoptimized + debuginfo] target(s) <span class="hljs-keyword">in</span> 1.71s
     Running `target/debug/calculator`
Args { inner: [<span class="hljs-string">"target/debug/toto"</span>, <span class="hljs-string">"fCC"</span>] }
</code></pre>
<p>The above shows that the <code>Args</code> struct contains a <code>field</code> called <code>inner</code> which consists of the location of the compiled binary, and the command line arguments passed to the program.</p>
<p>To access the argument values, you can use the <code>nth</code> method on the <code>args</code> variable. The <code>nth</code> method takes an <code>index</code> argument, and returns the value at that index wrapped in an <code>Option</code>. So, the value needs to be unwrapped.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
  <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> args: Args = args();

  <span class="hljs-keyword">let</span> first: <span class="hljs-built_in">String</span> = args.nth(<span class="hljs-number">1</span>).unwrap();
}
</code></pre>
<p>The <code>args</code> variable needs to be declared as mutable, because the <code>nth</code> method mutable iterates over the elements, and removes the element accessed.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
  <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> args: Args = args();

  <span class="hljs-comment">// The first argument is the location of the compiled binary, so skip it</span>
  <span class="hljs-keyword">let</span> first: <span class="hljs-built_in">String</span> = args.nth(<span class="hljs-number">1</span>).unwrap();
  <span class="hljs-comment">// After accessing the second argument, the iterator's next element becomes the first</span>
  <span class="hljs-keyword">let</span> operator: <span class="hljs-built_in">String</span> = args.nth(<span class="hljs-number">0</span>).unwrap();
  <span class="hljs-keyword">let</span> second: <span class="hljs-built_in">String</span> = args.nth(<span class="hljs-number">0</span>).unwrap();

  <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{} {} {}"</span>, first, operator, second);
}
</code></pre>
<pre><code class="lang-bash">$ cargo run -- 1 + 1
   Compiling calculator v0.1.0 (/home/runner/Rust-in-Replit/calculator)
    Finished dev [unoptimized + debuginfo] target(s) <span class="hljs-keyword">in</span> 1.71s
     Running `target/debug/calculator`
1 + 1
</code></pre>
<h4 id="heading-step-5-parse-strings-into-numbers">Step 5 – Parse Strings into Numbers</h4>
<p>The <code>first</code> and <code>second</code> variables are strings, and you need to parse them into numbers. The <code>String</code> struct implements the <code>parse</code> method, which takes a type annotation, and returns a <code>Result</code> containing the parsed value.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::env::{args, Args};

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
  <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> args: Args = args();

  <span class="hljs-keyword">let</span> first: <span class="hljs-built_in">String</span> = args.nth(<span class="hljs-number">1</span>).unwrap();
  <span class="hljs-keyword">let</span> operator: <span class="hljs-built_in">String</span> = args.nth(<span class="hljs-number">0</span>).unwrap();
  <span class="hljs-keyword">let</span> second: <span class="hljs-built_in">String</span> = args.nth(<span class="hljs-number">0</span>).unwrap();

  <span class="hljs-keyword">let</span> first_number = first.parse::&lt;<span class="hljs-built_in">f32</span>&gt;().unwrap();
  <span class="hljs-keyword">let</span> second_number = second.parse::&lt;<span class="hljs-built_in">f32</span>&gt;().unwrap();

  <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{} {} {}"</span>, first_number, operator, second_number);
}
</code></pre>
<p>The above <code>parse</code> method uses the <em>turbofish</em> syntax to specify the type to try to parse the string into.</p>
<h4 id="heading-step-6-perform-basic-arithmetic-operations">Step 6 – Perform Basic Arithmetic Operations</h4>
<p>Rust uses the standard operators for addition, subtraction, multiplication, and division. </p>
<p>To handle the operations, you define a function named <code>operate</code> which will take three arguments: the operator as a <code>char</code>, and the two numbers as <code>f32</code>s. The function should also return an <code>f32</code> representing the outcome of the operation.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">operate</span></span>(operator: <span class="hljs-built_in">char</span>, first_number: <span class="hljs-built_in">f32</span>, second_number: <span class="hljs-built_in">f32</span>) -&gt; <span class="hljs-built_in">f32</span> {
  <span class="hljs-keyword">match</span> operator {
    <span class="hljs-string">'+'</span> =&gt; first_number + second_number,
    <span class="hljs-string">'-'</span> =&gt; first_number - second_number,
    <span class="hljs-string">'/'</span> =&gt; first_number / second_number,
    <span class="hljs-string">'*'</span> | <span class="hljs-string">'X'</span> | <span class="hljs-string">'x'</span> =&gt; first_number * second_number,
    _ =&gt; <span class="hljs-built_in">panic!</span>(<span class="hljs-string">"Invalid operator used."</span>),
  }
}
</code></pre>
<p>The <code>match</code> expression works similarly to a <code>switch</code> statement in other languages. The <code>match</code> expression takes a value, and a list of <em>arms</em>. Each <em>arm</em> is a pattern and block. The pattern is a value to match against, and the block is the code to execute if the pattern matches. The <code>_</code> pattern is a wildcard, acting like an <code>else</code> clause.</p>
<p>The multiplication arm includes the <code>OR</code> comparison to allow cases for <code>X</code> and <code>x</code> to be handled.</p>
<p>Now, to call <code>operate</code> with the <code>operator</code>, you need to converted it into a <code>char</code> first. You do this with the <code>chars</code> method on the <code>String</code> struct which returns an iterator over the characters in the string. Then, the first character is unwrapped:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
  <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> args: Args = args();

  <span class="hljs-keyword">let</span> first: <span class="hljs-built_in">String</span> = args.nth(<span class="hljs-number">1</span>).unwrap();
  <span class="hljs-keyword">let</span> operator: <span class="hljs-built_in">char</span> = args.nth(<span class="hljs-number">0</span>).unwrap().chars().next().unwrap();
  <span class="hljs-keyword">let</span> second: <span class="hljs-built_in">String</span> = args.nth(<span class="hljs-number">0</span>).unwrap();

  <span class="hljs-keyword">let</span> first_number = first.parse::&lt;<span class="hljs-built_in">f32</span>&gt;().unwrap();
  <span class="hljs-keyword">let</span> second_number = second.parse::&lt;<span class="hljs-built_in">f32</span>&gt;().unwrap();
  <span class="hljs-keyword">let</span> result = operate(operator, first_number, second_number);

  <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{} {} {}"</span>, first_number, operator, second_number);
}
</code></pre>
<p>The return of <code>operate</code> is stored in the <code>result</code> variable.</p>
<h4 id="heading-step-7-format-the-output">Step 7 – Format the Output</h4>
<p>To get the desired output, the <code>first_number</code>, <code>second_number</code>, <code>operator</code>, and <code>result</code> variables need to be formatted. You can use the <code>format!</code> macro to create a <code>String</code> from a format string and a list of arguments:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">output</span></span>(first_number: <span class="hljs-built_in">f32</span>, operator: <span class="hljs-built_in">char</span>, second_number: <span class="hljs-built_in">f32</span>, result: <span class="hljs-built_in">f32</span>) -&gt; <span class="hljs-built_in">String</span> {
  <span class="hljs-built_in">format!</span>(
    <span class="hljs-string">"{} {} {} = {}"</span>,
    first_number, operator, second_number, result
  )
}
</code></pre>
<h4 id="heading-step-8-bring-it-all-together">Step 8 – Bring It All Together</h4>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::env::{args, Args};

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
  <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> args: Args = args();

  <span class="hljs-keyword">let</span> first: <span class="hljs-built_in">String</span> = args.nth(<span class="hljs-number">1</span>).unwrap();
  <span class="hljs-keyword">let</span> operator: <span class="hljs-built_in">char</span> = args.nth(<span class="hljs-number">0</span>).unwrap().chars().next().unwrap();
  <span class="hljs-keyword">let</span> second: <span class="hljs-built_in">String</span> = args.nth(<span class="hljs-number">0</span>).unwrap();

  <span class="hljs-keyword">let</span> first_number = first.parse::&lt;<span class="hljs-built_in">f32</span>&gt;().unwrap();
  <span class="hljs-keyword">let</span> second_number = second.parse::&lt;<span class="hljs-built_in">f32</span>&gt;().unwrap();
  <span class="hljs-keyword">let</span> result = operate(operator, first_number, second_number);

  <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, output(first_number, operator, second_number, result));
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">output</span></span>(first_number: <span class="hljs-built_in">f32</span>, operator: <span class="hljs-built_in">char</span>, second_number: <span class="hljs-built_in">f32</span>, result: <span class="hljs-built_in">f32</span>) -&gt; <span class="hljs-built_in">String</span> {
  <span class="hljs-built_in">format!</span>(
    <span class="hljs-string">"{} {} {} = {}"</span>,
    first_number, operator, second_number, result
  )
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">operate</span></span>(operator: <span class="hljs-built_in">char</span>, first_number: <span class="hljs-built_in">f32</span>, second_number: <span class="hljs-built_in">f32</span>) -&gt; <span class="hljs-built_in">f32</span> {
  <span class="hljs-keyword">match</span> operator {
    <span class="hljs-string">'+'</span> =&gt; first_number + second_number,
    <span class="hljs-string">'-'</span> =&gt; first_number - second_number,
    <span class="hljs-string">'/'</span> =&gt; first_number / second_number,
    <span class="hljs-string">'*'</span> | <span class="hljs-string">'X'</span> | <span class="hljs-string">'x'</span> =&gt; first_number * second_number,
    _ =&gt; <span class="hljs-built_in">panic!</span>(<span class="hljs-string">"Invalid operator used."</span>),
  }
}
</code></pre>
<p>To build the code into an executable binary, run the following command:</p>
<pre><code class="lang-bash">$ cargo build --release
   Compiling calculator v0.1.0 (/home/runner/Rust-in-Replit/calculator)
    Finished release [optimized] target(s) <span class="hljs-keyword">in</span> 3.26s
</code></pre>
<p>The <code>--release</code> flag tells Cargo to build the binary in release mode. This will reduce the size of the binary, and will also remove any debugging information.</p>
<p>The binary is built in the <code>target/release</code> directory. To run the binary, and test your application, run the following command:</p>
<pre><code class="lang-bash">$ target/release/calculator 1 + 1
1 + 1 = 2
</code></pre>
<h2 id="heading-project-2-build-an-image-combiner-in-rust">Project #2 – Build an Image Combiner in Rust</h2>
<h3 id="heading-project-outcome-1">Project Outcome</h3>
<p>At the end of this project, you will be able to combine two images using the command line.</p>
<p>Here is an example of an expected input:</p>
<pre><code class="lang-bash">$ combiner ./image1.png ./image2.png ./output.png
</code></pre>
<p>For an example of the output, look no further than the first image in this article ☝️</p>
<h3 id="heading-image-combiner-project-methodology">Image Combiner Project Methodology</h3>
<h4 id="heading-step-1-create-a-new-project-1">Step 1 - Create a New Project</h4>
<p>Use Cargo to create a new project named <code>combiner</code>:</p>
<pre><code class="lang-bash">$ cargo new combiner
</code></pre>
<h4 id="heading-step-2-add-a-new-module-for-args">Step 2 - Add a New Module for Args</h4>
<p>To prevent the <code>main.rs</code> file from becoming too overwhelming, create a new file named <code>args.rs</code> in the <code>src</code> directory.</p>
<p>Within <code>args.rs</code>, create a function named <code>get_nth_arg</code> which takes a <code>usize</code>, <code>n</code>, and returns a <code>String</code>. Then, from the <code>std::env</code> module, call the <code>args</code> function, and chain the <code>nth</code> method to get the <code>n</code>th argument, unwrapping the value:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_nth_arg</span></span>(n: <span class="hljs-built_in">usize</span>) -&gt; <span class="hljs-built_in">String</span> {
  std::env::args().nth(n).unwrap()
}
</code></pre>
<p>Define a public struct named <code>Args</code> which consists of three public fields of type <code>String</code>: <code>image_1</code>, <code>image_2</code>, and <code>output</code>:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Args</span></span> {
  <span class="hljs-keyword">pub</span> image_1: <span class="hljs-built_in">String</span>,
  <span class="hljs-keyword">pub</span> image_2: <span class="hljs-built_in">String</span>,
  <span class="hljs-keyword">pub</span> output: <span class="hljs-built_in">String</span>,
}
</code></pre>
<p>Declare the struct and its fields as public with the <code>pub</code> keyword so you can access them from outside the <code>args.rs</code> file.</p>
<p>Lastly, you can use the <code>get_nth_arg</code> function to create a new <code>Args</code> struct in a <code>new</code> function:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> Args {
  <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>() -&gt; <span class="hljs-keyword">Self</span> {
    Args {
      image_1: get_nth_arg(<span class="hljs-number">1</span>),
      image_2: get_nth_arg(<span class="hljs-number">2</span>),
      output: get_nth_arg(<span class="hljs-number">3</span>),
    }
  }
}
</code></pre>
<p>All together, the <code>args.rs</code> file looks like this:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Args</span></span> {
  <span class="hljs-keyword">pub</span> image_1: <span class="hljs-built_in">String</span>,
  <span class="hljs-keyword">pub</span> image_2: <span class="hljs-built_in">String</span>,
  <span class="hljs-keyword">pub</span> output: <span class="hljs-built_in">String</span>,
}

<span class="hljs-keyword">impl</span> Args {
  <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>() -&gt; <span class="hljs-keyword">Self</span> {
    Args {
      image_1: get_nth_arg(<span class="hljs-number">1</span>),
      image_2: get_nth_arg(<span class="hljs-number">2</span>),
      output: get_nth_arg(<span class="hljs-number">3</span>),
    }
  }
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_nth_arg</span></span>(n: <span class="hljs-built_in">usize</span>) -&gt; <span class="hljs-built_in">String</span> {
  std::env::args().nth(n).unwrap()
}
</code></pre>
<h4 id="heading-step-3-import-and-use-the-args-module">Step 3 – Import and Use the <code>args</code> Module</h4>
<p>Within <code>main.rs</code>, you need to declare the <code>args.rs</code> file as a module. Then, to use the <code>Args</code> struct, you need to import it:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">mod</span> args;
<span class="hljs-keyword">use</span> args::Args;

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
  <span class="hljs-keyword">let</span> args = Args::new();
  <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, args);
}
</code></pre>
<p>But testing the code reveals an error:</p>
<pre><code class="lang-bash">$ cargo run -- arg1 arg2 arg3
   Compiling combiner v0.1.0 (/home/runner/Rust-in-Replit/combiner)
error[E0277]: `args::Args` doesn<span class="hljs-string">'t implement `Debug`
  --&gt; src/main.rs:12:20
   |
12 |   println!("{:?}", args);
   |                    ^^^^ `args::Args` cannot be formatted using `{:?}`
   |
   = help: the trait `Debug` is not implemented for `args::Args`
   = note: add `#[derive(Debug)]` or manually implement `Debug`
   = note: required by `std::fmt::Debug::fmt`
   = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.
error: could not compile `combiner`

To learn more, run the command again with --verbose.</span>
</code></pre>
<p>Similarly to how functions are implemented for structs, traits can be implemented for structs. However, the <code>Debug</code> trait is special in that it can be implemented using attributes:</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Debug)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Args</span></span> {
  <span class="hljs-keyword">pub</span> image_1: <span class="hljs-built_in">String</span>,
  <span class="hljs-keyword">pub</span> image_2: <span class="hljs-built_in">String</span>,
  <span class="hljs-keyword">pub</span> output: <span class="hljs-built_in">String</span>,
}
</code></pre>
<p>The <code>Debug</code> trait has been <em>derived</em> for the <code>Args</code> struct. This means that the <code>Debug</code> trait is automatically implemented for the struct, without you having to manually implement it 🚀.</p>
<p>Now, running the code works:</p>
<pre><code class="lang-bash">$ cargo run -- arg1 arg2 arg3
    Finished dev [unoptimized + debuginfo] target(s) <span class="hljs-keyword">in</span> 0.01s
     Running `target/debug/combiner arg1 arg2 arg3`
Args { image_1: <span class="hljs-string">"arg1"</span>, image_2: <span class="hljs-string">"arg2"</span>, output: <span class="hljs-string">"arg3"</span> }
</code></pre>
<h4 id="heading-step-4-add-an-external-crate">Step 4 – Add an External Crate</h4>
<p>In much the same way other languages have libraries or packages, Rust has crates. In order to encode and decode images, you can use the <code>image</code> crate.</p>
<p>Add the <code>image</code> crate with version <code>0.23.14</code> to the <code>Cargo.toml</code> file:</p>
<pre><code class="lang-toml"><span class="hljs-section">[package]</span>
<span class="hljs-attr">name</span> = <span class="hljs-string">"combiner"</span>
<span class="hljs-attr">version</span> = <span class="hljs-string">"0.1.0"</span>
<span class="hljs-attr">edition</span> = <span class="hljs-string">"2018"</span>

<span class="hljs-comment"># See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html</span>

<span class="hljs-section">[dependencies]</span>
<span class="hljs-attr">image</span> = <span class="hljs-string">"0.23.14"</span>
</code></pre>
<p>Now, when <code>cargo run</code> is next called, Cargo will fetch and install the <code>image</code> crate.</p>
<h4 id="heading-step-5-read-an-image-file">Step 5 – Read an Image File</h4>
<p>The <code>image</code> crate comes with an <code>io</code> module including a <code>Reader</code> struct. This struct implements an <code>open</code> function which takes a path to an image file, and returns a <code>Result</code> containing a <em>reader</em>. You can format and decode this reader to yield the image format (for example PNG, JGP, and so on) and the image data.</p>
<p>Create a function named <code>find_image_from_path</code> to open the image file from a <code>path</code> argument:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">find_image_from_path</span></span>(path: <span class="hljs-built_in">String</span>) -&gt; (DynamicImage, ImageFormat) {
  <span class="hljs-keyword">let</span> image_reader: Reader&lt;BufReader&lt;File&gt;&gt; = Reader::open(path).unwrap();
  <span class="hljs-keyword">let</span> image_format: ImageFormat = image_reader.format().unwrap();
  <span class="hljs-keyword">let</span> image: DynamicImage = image_reader.decode().unwrap();
  (image, image_format)
}
</code></pre>
<p>The <code>image</code> and <code>image_format</code> variables are returned as a tuple.</p>
<p>Include the necessary imports at the top of the file:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> image::{ io::Reader, DynamicImage, ImageFormat };

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
  <span class="hljs-comment">// ...</span>
  <span class="hljs-keyword">let</span> (image_1, image_1_format) = find_image_from_path(args.image_1);
  <span class="hljs-keyword">let</span> (image_2, image_2_format) = find_image_from_path(args.image_2);
}
</code></pre>
<p>Within <code>main</code>, the returned tuple can be destructured into two new variables for each image path.</p>
<h4 id="heading-step-6-handle-errors-with-result">Step 6 – Handle Errors with <code>Result</code></h4>
<p>It is important to be able to handle errors that come up. For example, you might have a case where two images of different formats are given as arguments to combine.</p>
<p>A semantic way of handling such an error is to return a <code>Result</code> which can consist of either an <code>Ok</code> or an <code>Err</code>.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() -&gt; <span class="hljs-built_in">Result</span>&lt;(), ImageDataErrors&gt; {
  <span class="hljs-keyword">let</span> args = Args::new();
  <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, args);

  <span class="hljs-keyword">let</span> (image_1, image_1_format) = find_image_from_path(args.image_1);
  <span class="hljs-keyword">let</span> (image_2, image_2_format) = find_image_from_path(args.image_2);

  <span class="hljs-keyword">if</span> image_1_format != image_2_format {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">Err</span>(ImageDataErrors::DifferentImageFormats);
  }
  <span class="hljs-literal">Ok</span>(())
}
</code></pre>
<p>The <code>main</code> function returns an <code>Err</code> containing an enum with unit variant <code>DifferentImageFormats</code> if the two image formats are not equal. Otherwise, it returns an <code>Ok</code> with an empty tuple.</p>
<p>The enum is defined as:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">ImageDataErrors</span></span> {
  DifferentImageFormats,
}
</code></pre>
<h4 id="heading-step-7-resize-the-images-to-match">Step 7 – Resize the Images to Match</h4>
<p>To make combining the images easier, you resize the largest image to match the smallest image.</p>
<p>First, you can find the smallest image using the <code>dimensions</code> method which returns the width and height of the image as a tuple. These tuples can be compared, and the smallest returned:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_smallest_dimensions</span></span>(dim_1: (<span class="hljs-built_in">u32</span>, <span class="hljs-built_in">u32</span>), dim_2: (<span class="hljs-built_in">u32</span>, <span class="hljs-built_in">u32</span>)) -&gt; (<span class="hljs-built_in">u32</span>, <span class="hljs-built_in">u32</span>) {
  <span class="hljs-keyword">let</span> pix_1 = dim_1.<span class="hljs-number">0</span> * dim_1.<span class="hljs-number">1</span>;
  <span class="hljs-keyword">let</span> pix_2 = dim_2.<span class="hljs-number">0</span> * dim_2.<span class="hljs-number">1</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">if</span> pix_1 &lt; pix_2 { dim_1 } <span class="hljs-keyword">else</span> { dim_2 };
}
</code></pre>
<p>The tuple values are accessed using dot-notation from zero-based indexing.</p>
<p>If <code>image_2</code> is the smallest image, then <code>image_1</code> needs to be resized to match the smallest dimensions. Otherwise, <code>image_2</code> needs to be resized.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">standardise_size</span></span>(image_1: DynamicImage, image_2: DynamicImage) -&gt; (DynamicImage, DynamicImage) {
  <span class="hljs-keyword">let</span> (width, height) = get_smallest_dimensions(image_1.dimensions(), image_2.dimensions());
  <span class="hljs-built_in">println!</span>(<span class="hljs-string">"width: {}, height: {}\n"</span>, width, height);

  <span class="hljs-keyword">if</span> image_2.dimensions() == (width, height) {
    (image_1.resize_exact(width, height, Triangle), image_2)
  } <span class="hljs-keyword">else</span> {
    (image_1, image_2.resize_exact(width, height, Triangle))
  }
}
</code></pre>
<p>The <code>resize_exact</code> method implemented on the <code>DynamicImage</code> struct mutably borrows the image, and, using the <code>width</code>, <code>height</code>, and <code>FilterType</code> arguments, resizes the image.</p>
<p>Using the return of the <code>standardise_size</code> function, you can redeclare the <code>image_1</code> and <code>image_2</code> variables:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> image::{ io::Reader, DynamicImage, ImageFormat, imageops::FilterType::Triangle };

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() -&gt; <span class="hljs-built_in">Result</span>&lt;(), ImageDataErrors&gt; {
  <span class="hljs-comment">// ...</span>
  <span class="hljs-keyword">let</span> (image_1, image_2) = standardise_size(image_1, image_2);
  <span class="hljs-literal">Ok</span>(())
}
</code></pre>
<h4 id="heading-step-8-create-a-floating-image">Step 8 – Create a Floating Image</h4>
<p>To handle the output, create a temporary struct to hold the metadata for the output image.</p>
<p>Define a struct named <code>FloatingImage</code> to hold the <code>width</code>, <code>height</code>, and <code>data</code> of the image, as well as the <code>name</code> of the output file:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">FloatingImage</span></span> {
  width: <span class="hljs-built_in">u32</span>,
  height: <span class="hljs-built_in">u32</span>,
  data: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt;,
  name: <span class="hljs-built_in">String</span>,
}
</code></pre>
<p>Next, implement a <code>new</code> function for <code>FloatingImage</code> which takes values for the <code>width</code>, <code>height</code>, and <code>name</code> of the output image:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> FloatingImage {
  <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>(width: <span class="hljs-built_in">u32</span>, height: <span class="hljs-built_in">u32</span>, name: <span class="hljs-built_in">String</span>) -&gt; <span class="hljs-keyword">Self</span> {
    <span class="hljs-keyword">let</span> buffer_capacity = <span class="hljs-number">3_655_744</span>;
    <span class="hljs-keyword">let</span> buffer: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt; = <span class="hljs-built_in">Vec</span>::with_capacity(buffer_capacity);
    FloatingImage {
      width,
      height,
      data: buffer,
      name,
    }
  }
}
</code></pre>
<p>As you haven't created the data for the image yet, create a buffer in the form of a <code>Vec</code> of <code>u8</code>s with a capacity of 3,655,744 (956 x 956 x 4). The <code>&lt;number&gt;_&lt;number&gt;</code> syntax is Rust's easy-to-read numbering which separates the number into groups or three digits.</p>
<p>Use the <code>image_1</code> variable's <code>width</code> and <code>height</code> values to create an instance of the <code>FloatingImage</code>, and use the third argument stored in <code>args</code> to set the name of the <code>FloatingImage</code>:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() -&gt; <span class="hljs-built_in">Result</span>&lt;(), ImageDataErrors&gt; {
  <span class="hljs-comment">// ...</span>
  <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> output = FloatingImage::new(image_1.width(), image_1.height(), args.output);
  <span class="hljs-literal">Ok</span>(())
}
</code></pre>
<p>Declare the <code>output</code> variables as mutable so you can modify the <code>data</code> field later.</p>
<h4 id="heading-step-9-create-the-combined-image-data">Step 9 – Create the Combined Image Data</h4>
<p>In order to process the images, you need to convert them into a vector of RGBA pixels. The pixels are stored as <code>u8</code>s, because their values are between 0 and 255.</p>
<p>The <code>DynamicImage</code> struct implements the <code>to_rgba8</code> method, which returns an <code>ImageBuffer</code> containing a <code>Vec&lt;u8&gt;</code>, and the <code>ImageBuffer</code> implements the <code>into_vec</code> method, which returns the <code>Vec&lt;u8&gt;</code>:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">combine_images</span></span>(image_1: DynamicImage, image_2: DynamicImage) -&gt; <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt; {
  <span class="hljs-keyword">let</span> vec_1 = image_1.to_rgba8().into_vec();
  <span class="hljs-keyword">let</span> vec_2 = image_2.to_rgba8().into_vec();

  alternate_pixels(vec_1, vec_2)
}
</code></pre>
<p>Next, the <code>vec_1</code> and <code>vec_2</code> variables are passed to the <code>alternate_pixels</code> function which returns the combined image data by alternating the RGBA pixel sets of the two images:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">alternate_pixels</span></span>(vec_1: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt;, vec_2: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt;) -&gt; <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt; {
  <span class="hljs-comment">// A Vec&lt;u8&gt; is created with the same length as vec_1</span>
  <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> combined_data = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">0u8</span>; vec_1.len()];

  <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> i = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">while</span> i &lt; vec_1.len() {
    <span class="hljs-keyword">if</span> i % <span class="hljs-number">8</span> == <span class="hljs-number">0</span> {
      combined_data.splice(i..=i + <span class="hljs-number">3</span>, set_rgba(&amp;vec_1, i, i + <span class="hljs-number">3</span>));
    } <span class="hljs-keyword">else</span> {
      combined_data.splice(i..=i + <span class="hljs-number">3</span>, set_rgba(&amp;vec_2, i, i + <span class="hljs-number">3</span>));
    }
    i += <span class="hljs-number">4</span>;
  }

  combined_data
}
</code></pre>
<p>The <code>set_rgba</code> function takes a reference to a <code>Vec&lt;u8&gt;</code>, and returns the RGBA pixel set for that <code>Vec&lt;u8&gt;</code> starting and ending at a given index:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">set_rgba</span></span>(vec: &amp;<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt;, start: <span class="hljs-built_in">usize</span>, end: <span class="hljs-built_in">usize</span>) -&gt; <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt; {
  <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> rgba = <span class="hljs-built_in">Vec</span>::new();
  <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> start..=end {
    <span class="hljs-keyword">let</span> val = <span class="hljs-keyword">match</span> vec.get(i) {
      <span class="hljs-literal">Some</span>(d) =&gt; *d,
      <span class="hljs-literal">None</span> =&gt; <span class="hljs-built_in">panic!</span>(<span class="hljs-string">"Index out of bounds"</span>),
    };
    rgba.push(val);
  }
  rgba
}
</code></pre>
<p>The <code>..=</code> syntax is Rust's range syntax which allows the range to be inclusive of the end value. The <code>*</code> symbol before a variable is Rust's dereferencing operator, which allows the value of the variable to be accessed.</p>
<p>Then, assign the return of <code>combine_images</code> to the <code>combined_data</code> variable:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() -&gt; <span class="hljs-built_in">Result</span>&lt;(), ImageDataErrors&gt; {
  <span class="hljs-comment">// ...</span>
  <span class="hljs-keyword">let</span> combined_data = combine_images(image_1, image_2);
  <span class="hljs-literal">Ok</span>(())
}
</code></pre>
<h4 id="heading-step-10-attach-the-combined-data-to-the-floating-image">Step 10 – Attach the Combined Data to the Floating Image</h4>
<p>To set the data of <code>combined_data</code> into the <code>output</code> image, a method on <code>FloatingImage</code> is defined to set the <code>data</code> field of <code>output</code> to the value of <code>combined_data</code>.</p>
<p>So far, you've only implemented functions on structs. Methods are defined in a similar way, but they take an instance of the struct as their first argument:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MyStruct</span></span> {
  name: <span class="hljs-built_in">String</span>,
}
<span class="hljs-keyword">impl</span> MyStruct {
  <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">change_name</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, new_name: &amp;<span class="hljs-built_in">str</span>) {
    <span class="hljs-keyword">self</span>.name = new_name.to_string();
  }
}

<span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> my_struct = MyStruct { name: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Shaun"</span>) };
<span class="hljs-comment">// my_struct.name == "Shaun"</span>
my_struct.change_name(<span class="hljs-string">"Tom"</span>);
<span class="hljs-comment">// my_struct.name == "Tom"</span>
</code></pre>
<p>Since you need to change the value of the instance of <code>FloatingImage</code>, the method <code>set_data</code> takes a mutable reference to the instance as its first argument.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> FloatingImage {
  <span class="hljs-comment">// ...</span>
  <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">set_data</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, data: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt;) -&gt; <span class="hljs-built_in">Result</span>&lt;(), ImageDataErrors&gt; {
    <span class="hljs-comment">// If the previously assigned buffer is too small to hold the new data</span>
    <span class="hljs-keyword">if</span> data.len() &gt; <span class="hljs-keyword">self</span>.data.capacity() {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">Err</span>(ImageDataErrors::BufferTooSmall);
    }
    <span class="hljs-keyword">self</span>.data = data;
    <span class="hljs-literal">Ok</span>(())
  }
}
</code></pre>
<p>The enum needs to be extended to include the new unit variant <code>BufferTooSmall</code>:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">ImageDataErrors</span></span> {
  <span class="hljs-comment">// ...</span>
  BufferTooSmall,
}
</code></pre>
<p><em>Notice:</em> The method is still only called with one argument:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() -&gt; <span class="hljs-built_in">Result</span>&lt;(), ImageDataErrors&gt; {
  <span class="hljs-comment">// ...</span>
  output.set_data(combined_data)?;
  <span class="hljs-literal">Ok</span>(())
}
</code></pre>
<p>The <code>?</code> syntax at the end of an expression is a shorthand way of handling the result of a function call. If the function call returns an error, the <em>error propagation</em> operator will return the error from the function call.</p>
<h4 id="heading-step-11-write-the-image-to-a-file">Step 11 – Write the Image to a File</h4>
<p>Finally, save the new image to a file. The <code>image</code> crate has a <code>save_buffer_with_format</code> function taking the following form:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">save_buffer_with_format</span></span>(
    path: <span class="hljs-built_in">AsRef</span>&lt;Path&gt;,
    buf: &amp;[<span class="hljs-built_in">u8</span>],
    width: <span class="hljs-built_in">u32</span>,
    height: <span class="hljs-built_in">u32</span>,
    color: image::ColorType,
    format: image::ImageFormat
  ) -&gt; image::ImageResult&lt;()&gt;;
</code></pre>
<p>Seeing as <code>AsRef</code> is implemented for <code>String</code>, you can use an argument of type <code>String</code> for the <code>path</code>.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() -&gt; <span class="hljs-built_in">Result</span>&lt;(), ImageDataErrors&gt; {
  <span class="hljs-comment">// ...</span>
  image::save_buffer_with_format(
    output.name,
    &amp;output.data,
    output.width,
    output.height,
    image::ColorType::Rgba8,
    image_1_format,
  )
  .unwrap();
  <span class="hljs-literal">Ok</span>(())
}
</code></pre>
<h4 id="heading-step-12-bring-it-all-together">Step 12 – Bring It All Together</h4>
<p>Here's the final code:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">mod</span> args;

<span class="hljs-keyword">use</span> args::Args;
<span class="hljs-keyword">use</span> image::{
  imageops::FilterType::Triangle, io::Reader, DynamicImage, GenericImageView, ImageFormat,
};

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() -&gt; <span class="hljs-built_in">Result</span>&lt;(), ImageDataErrors&gt; {
  <span class="hljs-keyword">let</span> args = Args::new();
  <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, args);

  <span class="hljs-keyword">let</span> (image_1, image_1_format) = find_image_from_path(args.image_1);
  <span class="hljs-keyword">let</span> (image_2, image_2_format) = find_image_from_path(args.image_2);

  <span class="hljs-keyword">if</span> image_1_format != image_2_format {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">Err</span>(ImageDataErrors::DifferentImageFormats);
  }

  <span class="hljs-keyword">let</span> (image_1, image_2) = standardise_size(image_1, image_2);
  <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> output = FloatingImage::new(image_1.width(), image_1.height(), args.output);

  <span class="hljs-keyword">let</span> combined_data = combine_images(image_1, image_2);

  output.set_data(combined_data)?;

  image::save_buffer_with_format(
    output.name,
    &amp;output.data,
    output.width,
    output.height,
    image::ColorType::Rgba8,
    image_1_format,
  )
  .unwrap();
  <span class="hljs-literal">Ok</span>(())
}

<span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">ImageDataErrors</span></span> {
  BufferTooSmall,
  DifferentImageFormats,
}

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">FloatingImage</span></span> {
  width: <span class="hljs-built_in">u32</span>,
  height: <span class="hljs-built_in">u32</span>,
  data: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt;,
  name: <span class="hljs-built_in">String</span>,
}

<span class="hljs-keyword">impl</span> FloatingImage {
  <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>(width: <span class="hljs-built_in">u32</span>, height: <span class="hljs-built_in">u32</span>, name: <span class="hljs-built_in">String</span>) -&gt; <span class="hljs-keyword">Self</span> {
    <span class="hljs-keyword">let</span> buffer_capacity = <span class="hljs-number">3_655_744</span>;
    <span class="hljs-keyword">let</span> buffer: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt; = <span class="hljs-built_in">Vec</span>::with_capacity(buffer_capacity);
    FloatingImage {
      width,
      height,
      data: buffer,
      name,
    }
  }
  <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">set_data</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, data: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt;) -&gt; <span class="hljs-built_in">Result</span>&lt;(), ImageDataErrors&gt; {
    <span class="hljs-keyword">if</span> data.len() &gt; <span class="hljs-keyword">self</span>.data.capacity() {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">Err</span>(ImageDataErrors::BufferTooSmall);
    }
    <span class="hljs-keyword">self</span>.data = data;
    <span class="hljs-literal">Ok</span>(())
  }
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">find_image_from_path</span></span>(path: <span class="hljs-built_in">String</span>) -&gt; (DynamicImage, ImageFormat) {
  <span class="hljs-keyword">let</span> image_reader = Reader::open(path).unwrap();
  <span class="hljs-keyword">let</span> image_format = image_reader.format().unwrap();
  <span class="hljs-keyword">let</span> image = image_reader.decode().unwrap();
  (image, image_format)
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">standardise_size</span></span>(image_1: DynamicImage, image_2: DynamicImage) -&gt; (DynamicImage, DynamicImage) {
  <span class="hljs-keyword">let</span> (width, height) = get_smallest_dimensions(image_1.dimensions(), image_2.dimensions());
  <span class="hljs-built_in">println!</span>(<span class="hljs-string">"width: {}, height: {}\n"</span>, width, height);
  <span class="hljs-keyword">if</span> image_2.dimensions() == (width, height) {
    (image_1.resize_exact(width, height, Triangle), image_2)
  } <span class="hljs-keyword">else</span> {
    (image_1, image_2.resize_exact(width, height, Triangle))
  }
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_smallest_dimensions</span></span>(dim_1: (<span class="hljs-built_in">u32</span>, <span class="hljs-built_in">u32</span>), dim_2: (<span class="hljs-built_in">u32</span>, <span class="hljs-built_in">u32</span>)) -&gt; (<span class="hljs-built_in">u32</span>, <span class="hljs-built_in">u32</span>) {
  <span class="hljs-keyword">let</span> pix_1 = dim_1.<span class="hljs-number">0</span> * dim_1.<span class="hljs-number">1</span>;
  <span class="hljs-keyword">let</span> pix_2 = dim_2.<span class="hljs-number">0</span> * dim_2.<span class="hljs-number">1</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">if</span> pix_1 &lt; pix_2 { dim_1 } <span class="hljs-keyword">else</span> { dim_2 };
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">combine_images</span></span>(image_1: DynamicImage, image_2: DynamicImage) -&gt; <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt; {
  <span class="hljs-keyword">let</span> vec_1 = image_1.to_rgba8().into_vec();
  <span class="hljs-keyword">let</span> vec_2 = image_2.to_rgba8().into_vec();

  alternate_pixels(vec_1, vec_2)
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">alternate_pixels</span></span>(vec_1: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt;, vec_2: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt;) -&gt; <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt; {
  <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> combined_data = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">0u8</span>; vec_1.len()];

  <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> i = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">while</span> i &lt; vec_1.len() {
    <span class="hljs-keyword">if</span> i % <span class="hljs-number">8</span> == <span class="hljs-number">0</span> {
      combined_data.splice(i..=i + <span class="hljs-number">3</span>, set_rgba(&amp;vec_1, i, i + <span class="hljs-number">3</span>));
    } <span class="hljs-keyword">else</span> {
      combined_data.splice(i..=i + <span class="hljs-number">3</span>, set_rgba(&amp;vec_2, i, i + <span class="hljs-number">3</span>));
    }
    i += <span class="hljs-number">4</span>;
  }

  combined_data
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">set_rgba</span></span>(vec: &amp;<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt;, start: <span class="hljs-built_in">usize</span>, end: <span class="hljs-built_in">usize</span>) -&gt; <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt; {
  <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> rgba = <span class="hljs-built_in">Vec</span>::new();
  <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> start..=end {
    <span class="hljs-keyword">let</span> val = <span class="hljs-keyword">match</span> vec.get(i) {
      <span class="hljs-literal">Some</span>(d) =&gt; *d,
      <span class="hljs-literal">None</span> =&gt; <span class="hljs-built_in">panic!</span>(<span class="hljs-string">"Index out of bounds"</span>),
    };
    rgba.push(val);
  }
  rgba
}
</code></pre>
<p>Building the binary:</p>
<pre><code class="lang-bash">$ cargo build --release
</code></pre>
<p>Creating a combined image, using the images in <a target="_blank" href="https://github.com/freeCodeCamp/Rust-In-Replit"><code>freeCodeCamp/Rust-In-Replit</code></a>:</p>
<pre><code class="lang-bash">$ ./target/release/combiner images/pro.png images/fcc_glyph.png images/output.png
</code></pre>
<p>And here's the result in <code>images/output.png</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/output.png" alt="Output combined image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>With that, you now know the basics of Rust.</p>
<p>There is still a lot to learn. So, watch this space for more content 😉.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
