<?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[ repl.it - 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[ repl.it - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 09 Jun 2026 10:26:07 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/replit/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Get GitHub Pro and Replit Hacker for Free as a Student ]]>
                </title>
                <description>
                    <![CDATA[ If you are in high school or college/university and are interested in coding, you should consider signing up for GitHub Education.  This allows you to use GitHub Pro, as well as having many other benefits.  In this quick guide, I'll show you the step... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-get-github-pro-and-replit-hacker-for-free-as-a-student/</link>
                <guid isPermaLink="false">66b8dd3547c23b7ae1ad0bbb</guid>
                
                    <category>
                        <![CDATA[ GitHub ]]>
                    </category>
                
                    <category>
                        <![CDATA[ repl.it ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Students ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Eesa Zahed ]]>
                </dc:creator>
                <pubDate>Fri, 10 Feb 2023 17:47:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/coderr.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you are in high school or college/university and are interested in coding, you should consider signing up for GitHub Education. </p>
<p>This allows you to use GitHub Pro, as well as having many other benefits. </p>
<p>In this quick guide, I'll show you the steps to sign up for GitHub Education and I'll discuss its benefits. Then I'll show you how you can get free access to Replit Hacker for a year. </p>
<h2 id="heading-how-to-get-a-free-github-pro-account-as-a-student">How to Get a Free GitHub Pro Account as a Student</h2>
<p>If you do not already have a <a target="_blank" href="https://github.com/signup">GitHub</a> account, you will need to create one. Sign in with your personal email address (so you can use your account even after your school email address gets deactivated when you graduate).</p>
<p>Next, go to settings and click Emails. Here is where you will add your school email to your GitHub account.</p>
<p><img src="https://user-images.githubusercontent.com/97064249/215526808-7e2aeb8a-c32c-4f33-9ef7-ad0f6b88d287.png" alt="image1" width="255" height="405" loading="lazy">
<em>Add your school email in your GitHub account</em></p>
<p>Add your school email address and verify it. Once it is verified, go to <a target="_blank" href="https://education.github.com/">https://education.github.com/</a>. This will allow you to be eligible for GitHub Pro. Sign in with your GitHub account.</p>
<p>Then, head to Benefits. Scroll down and click <strong>Get student benefits</strong> (just make sure you are <a target="_blank" href="https://education.github.com/discount_requests/pack_application#student-info">eligible</a> first).</p>
<p><img src="https://user-images.githubusercontent.com/97064249/215526941-b1a1e2fc-bcd9-4edd-bf8e-61a4e1cd82ac.png" alt="image2" width="437" height="329" loading="lazy">
<em>Student benefits</em></p>
<p>Select <strong>Student</strong> as your academic status. Scroll down and use your school email address. After that, you have to select your school name as your school. Using a few sentences, explain why you are using GitHub.</p>
<p>Once you have completed those steps, press continue.</p>
<p>You’ll need to verify you’re a student at your school. To do this, you can upload a screenshot of an email from your school board or another official school document. It’ll take a few days to verify, so you’ll have to wait until then.</p>
<p>After that has been completed, you should see your dashboard looking something like this:</p>
<p><img src="https://user-images.githubusercontent.com/97064249/215528452-d7f4de46-77ac-4df2-8352-f06329fdeb5f.png" alt="image3" width="1287" height="734" loading="lazy"></p>
<p>You'll now have access to many student benefits, including a $200 Digital Ocean credit, a free domain from Namecheap, and a free subscription to the JetBrains IDE, which you can renew annually. </p>
<p>Next in this tutorial, you will be learning how to get the Replit Hacker plan for free (which is not mentioned as a student benefit offer).</p>
<h2 id="heading-how-to-get-a-free-replit-hacker-plan">How to Get a Free Replit Hacker Plan</h2>
<p>Once you have GitHub Pro, you’ll have access to many other benefits as well. One of the most notable benefits is a free Replit Hacker Plan for one year.</p>
<p>If you don't know what Replit is, it's a web-based IDE which allows users to create amazing projects (called Repls) that are stored on the cloud. </p>
<p>I have found Replit incredibly useful for coding in Rust, as it makes installing packages and setting up the dev environment really simple and easy. </p>
<p>You can also import GitHub repositories directly into Replit, so you can work on your code from any device, as long as you have an internet connection.</p>
<p>Replit is free to sign up, but having the <strong>Hacker plan</strong> gives you certain benefits that are extremely useful for development. </p>
<p>One notable benefit is having unlimited private Repls. Some more advantages are having 10x the account storage, and double the Repl storage. This plan starts at $7.00 a month, but luckily for students, there is a way to get the plan for free (<a target="_blank" href="https://replit.com/site/github-students">Source</a>).</p>
<p>If you don’t have a Replit account, create one with your personal email address (so you can use your account even after you school email address gets deactivated when you graduate).</p>
<p>Next, head to Account in the home menu.</p>
<p><img src="https://user-images.githubusercontent.com/97064249/215528245-87cf3cae-db1f-4382-b75a-599c269cc95e.png" alt="image4" width="184" height="106" loading="lazy"></p>
<p>Scroll down to Connected services and connect your GitHub account.</p>
<p><img src="https://user-images.githubusercontent.com/97064249/215528283-8895bb3e-fb70-4d7c-87b3-3d3852e8c6c7.png" alt="image5" width="355" height="161" loading="lazy"></p>
<p>You should now have GitHub Pro (until you graduate) and Replit Hacker (for one year).</p>
<p>Enjoy!</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Now with your upgraded accounts, I hope you enjoy creating amazing things! Feel free to check out my <a target="_blank" href="https://github.com/eesazahed">GitHub</a> and <a target="_blank" href="https://replit.com/@eesazahed">Replit</a> to view my projects.</p>
<p>If you'd like to reach out, my email address is eszhd1 (at) gmail.com</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>
