<?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" version="2.0"><channel><title><![CDATA[Francesco Ciulla Blog]]></title><description><![CDATA[Francesco Ciulla Blog, Javascript and Docker]]></description><link>https://blog.francescociulla.com</link><generator>RSS for Node</generator><lastBuildDate>Wed, 15 Apr 2026 07:24:42 GMT</lastBuildDate><atom:link href="https://blog.francescociulla.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Should you learn Rust as your next programming language?]]></title><description><![CDATA[Hi, I want to focus on why you might be interested in learning Rust in this short article.
If you're reading this, you may already be interested in learning Rust. However, if not, I understand you. I am also very skeptical about learning new technolo...]]></description><link>https://blog.francescociulla.com/should-you-learn-rust-as-your-next-programming-language</link><guid isPermaLink="true">https://blog.francescociulla.com/should-you-learn-rust-as-your-next-programming-language</guid><category><![CDATA[Rust]]></category><category><![CDATA[rust lang]]></category><category><![CDATA[Rust programming]]></category><category><![CDATA[rustseries]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Fri, 09 May 2025 10:04:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1746784919544/cd841886-d751-4db0-b6b6-0b2da47082a5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hi, I want to focus on why you might be interested in learning Rust in this short article.</p>
<p>If you're reading this, you may already be interested in learning Rust. However, if not, I understand you. I am also very skeptical about learning new technologies. But I am here to try to change your mind.</p>
<p>Here are some reasons to consider it:</p>
<ol>
<li><p><strong>Performance</strong>: The main reason Rust has become popular is that <strong>it is</strong> designed to be fast and efficient. This makes it an excellent choice for performance-critical applications. It can often match (or exceed) the performance of C and C++ while providing additional safety features. I believe it strikes a good balance between performance and safety.</p>
</li>
<li><p><strong>Memory Safety</strong>: Rust is designed to be memory-safe. This helps avoid common programming errors like null pointer dereferences and buffer overflows. Rust achieves this through its ownership system, which enforces strict rules about how memory is accessed and shared. This is a valuable feature for developers who want to write safe and reliable code without worrying about low-level memory management!</p>
</li>
<li><p><strong>Concurrency</strong>: Writing concurrent code is usually a nightmare; however, Rust simplifies creating concurrent programs. Its strong type system and ownership model help prevent data races.</p>
</li>
<li><p><strong>Helpful (and annoying) Compiler &amp; Tooling</strong>: Rust's compiler is well-known for being very helpful. It does not just report random errors (I see you Java), it often explains them thoroughly and suggests how to fix your code. I like to compare it to that old annoying grandma who wants the best for you. You know she's annoying, but she is right. Plus, Rust comes with a fantastic tool called 'Cargo' that makes it easy to manage your project's dependencies and build your programs, simplifying the development process.</p>
</li>
</ol>
<p>Are you not convinced yet? Well, I kept the best shot as the last one:</p>
<p>Rust has been voted the most-admired programming language in the latest Stack Overflow survey. Do you want to base your future learning choices on what you read on Twitter, what a tech influencer says, or real data?</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i7vd2oq9aos6ewshsz90.png" alt="Stack Overflow Survey" /></p>
<p>If you are interested in learning Rust, I just <strong>published</strong> a <a target="_blank" href="https://youtu.be/gAX3Zj-JGE0">3.5-hour video on YouTube</a>; it's free and might help you understand the core concepts of the language. Good luck!</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/gAX3Zj-JGE0?si=PAsEvyhmUUoEiOhN"></iframe>

<p>Find me here: <a target="_blank" href="https://francescociulla.com">https://francescociulla.com</a></p>
]]></content:encoded></item><item><title><![CDATA[Iterators in Rust]]></title><description><![CDATA[Iterators in Rust provide a powerful and flexible way to process data efficiently by transforming, filtering, and aggregating elements in a collection. 
Unlike traditional loops, Rust’s iterators are lazy—meaning they don't perform any actions until ...]]></description><link>https://blog.francescociulla.com/iterators-in-rust</link><guid isPermaLink="true">https://blog.francescociulla.com/iterators-in-rust</guid><category><![CDATA[Rust]]></category><category><![CDATA[rust lang]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Tue, 15 Oct 2024 14:00:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1729000749222/8e1b4f83-a5a0-47df-82f8-0c6c18f479c4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Iterators in Rust provide a powerful and flexible way to process data efficiently by transforming, filtering, and aggregating elements in a collection. </p>
<p>Unlike traditional loops, Rust’s iterators are lazy—meaning they don't perform any actions until explicitly instructed to. This laziness makes iterators efficient because they only evaluate elements when needed, often combining multiple transformations into a single pass over the data.</p>
<p>In this lesson, we’ll dive into the core of Rust's iterator system and explore how to use methods like .map(), .filter(), and .fold() (similar to reduce) to create expressive, functional code.</p>
<p>If you prefer a video version:</p>
<iframe width="905" height="510" src="https://www.youtube.com/embed/Dtkv5i2nelk"></iframe>

<p>All the code is available on <a target="_blank" href="https://youtu.be/Dtkv5i2nelk">Github</a> (link in the video description)</p>
<p>You can find me here: https://francescociulla.com</p>
<h2 id="heading-introduction-to-iterators">Introduction to Iterators</h2>
<p>The iterator pattern allows you to perform tasks on a sequence of items in turn. An iterator handles the logic of moving from one item to the next and determines when the sequence has finished, freeing you from implementing that logic manually. In Rust, iterators are lazy, meaning they don’t do any work until you call methods that consume the iterator.</p>
<p>For Example:</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> v1 = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
    <span class="hljs-keyword">let</span> v1_iter = v1.iter();

    <span class="hljs-keyword">for</span> val <span class="hljs-keyword">in</span> v1_iter {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Got: {}"</span>, val);
    }
}
</code></pre>
<p>In this code, we create an iterator over a vector using the .iter() method. We then use a for loop to iterate over each value in the iterator and print it. The iterator pattern allows us to abstract away the logic of iterating through the vector, making our code more readable and expressive.</p>
<h2 id="heading-the-iterator-trait-and-the-next-method">The Iterator Trait and the next Method</h2>
<p>The Iterator trait is the core trait for iterators in Rust. It defines the behavior of the .next() method, which returns an Option containing the next value in the sequence. When the iterator is finished, .next() returns None.</p>
<p>All iterators in Rust implement the Iterator trait, which defines a single required method: next.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Iterator</span></span> {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Item</span></span>;

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">next</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Option</span>&lt;Self::Item&gt;;
}
</code></pre>
<ul>
<li><p>type Item: This is an associated type that specifies the type of items the iterator will yield.</p>
</li>
<li><p>next(): Advances the iterator and returns the next item, or None when the iterator is exhausted.</p>
</li>
</ul>
<p>For Example:</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> v1 = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> v1_iter = v1.iter();

    <span class="hljs-built_in">assert_eq!</span>(v1_iter.next(), <span class="hljs-literal">Some</span>(&amp;<span class="hljs-number">1</span>));
    <span class="hljs-built_in">assert_eq!</span>(v1_iter.next(), <span class="hljs-literal">Some</span>(&amp;<span class="hljs-number">2</span>));
    <span class="hljs-built_in">assert_eq!</span>(v1_iter.next(), <span class="hljs-literal">Some</span>(&amp;<span class="hljs-number">3</span>));
    <span class="hljs-built_in">assert_eq!</span>(v1_iter.next(), <span class="hljs-literal">None</span>);
}
</code></pre>
<p>In this code, we create an iterator over a vector and call the .next() method to get the next value in the sequence. We use the assert_eq! macro to check that the values returned by .next() are correct.</p>
<h2 id="heading-core-types-of-iterators">Core Types of Iterators</h2>
<p>Rust provides three main types of iterators: consuming adaptors, iterator adaptors, and iterators themselves. Consuming adaptors take ownership of the iterator and consume it, producing a single value. Iterator adaptors take an iterator and return a new iterator with a different behavior. Iterators themselves are the base trait for all iterators and define the behavior of the .next() method.</p>
<p>The three main types of iterators are:</p>
<ul>
<li><p>iter(): This method creates an iterator that borrows each element of the collection.</p>
</li>
<li><p>into_iter(): This method creates an iterator that takes ownership of each element of the collection.</p>
</li>
<li><p>iter_mut(): This method creates an iterator that mutably borrows each element of the collection.</p>
</li>
</ul>
<p>Let's see the purpose, ownership and use case of each iterator type:</p>
<h3 id="heading-iter">iter()</h3>
<ul>
<li><p>Purpose: This method creates an iterator that borrows each element of the collection.</p>
</li>
<li><p>Ownership: The original collection remains intact after calling iter().</p>
</li>
<li><p>Use Case: Use iter() when you want to iterate over the collection without taking ownership of it.</p>
</li>
</ul>
<p>For Example:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> numbers = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];

<span class="hljs-keyword">for</span> num <span class="hljs-keyword">in</span> numbers.iter() {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, num); <span class="hljs-comment">// Outputs each number</span>
}

<span class="hljs-built_in">println!</span>(<span class="hljs-string">"after iter: {:?}"</span>, numbers); <span class="hljs-comment">// Outputs: [1, 2, 3]</span>
</code></pre>
<h3 id="heading-itermut">iter_mut()</h3>
<ul>
<li><p>Purpose: This method creates an iterator that mutably borrows each element of the collection.</p>
</li>
<li><p>Ownership: The original collection remains intact after calling iter_mut().</p>
</li>
<li><p>Use Case: Use iter_mut() when you want to iterate over the collection and modify its elements.</p>
</li>
</ul>
<p>For Example:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> numbers = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">for</span> num <span class="hljs-keyword">in</span> numbers.iter_mut() {
    *num += <span class="hljs-number">1</span>; <span class="hljs-comment">// Mutates each element by adding 1</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, num);
}

<span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, numbers); <span class="hljs-comment">// Outputs: [2, 3, 4]</span>
</code></pre>
<h3 id="heading-intoiter">into_iter()</h3>
<ul>
<li><p>Purpose: This method creates an iterator that takes ownership of each element of the collection.</p>
</li>
<li><p>Ownership: The original collection is consumed after calling into_iter().</p>
</li>
<li><p>Use Case: Use into_iter() when you want to move each element out of the collection.</p>
</li>
</ul>
<p>For Example:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> numbers = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];

<span class="hljs-keyword">for</span> num <span class="hljs-keyword">in</span> numbers.into_iter() {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, num); <span class="hljs-comment">// Outputs each number</span>
}

<span class="hljs-comment">// println!("{:?}", numbers); // Error: `numbers` is no longer accessible</span>
</code></pre>
<h3 id="heading-summary-table-of-iterator-types">Summary table of iterator types:</h3>
<p>Here is a summary table of the three main types of iterators in Rust:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Iterator Type</td><td>Purpose</td><td>Ownership</td><td>Use Case</td></tr>
</thead>
<tbody>
<tr>
<td>iter()</td><td>Creates an iterator that borrows each element of the collection.</td><td>Original collection remains intact.</td><td>Iterate over the collection without taking ownership.</td></tr>
<tr>
<td>iter_mut()</td><td>Creates an iterator that mutably borrows each element of the collection.</td><td>Original collection remains intact.</td><td>Iterate over the collection and modify its elements.</td></tr>
<tr>
<td>into_iter()</td><td>Creates an iterator that takes ownership of each element of the collection.</td><td>Original collection is consumed.</td><td>Move each element out of the collection.</td></tr>
</tbody>
</table>
</div><h2 id="heading-methods-to-modify-or-consume-iterators-map-filter-and-fold">Methods to Modify or Consume Iterators: .map(), .filter(), and .fold()</h2>
<p>Rust provides a variety of methods to modify or consume iterators, allowing you to transform, filter, and aggregate elements efficiently. These methods are called iterator adaptors and are chained together to create expressive, functional code.</p>
<p>Some common iterator adaptors include:</p>
<ul>
<li>.map(): Transforms each element in the iterator.</li>
<li>.filter(): Filters elements based on a predicate function.</li>
<li>.fold(): Aggregates elements into a single value.</li>
</ul>
<p>Let's explore each of these methods in more detail:</p>
<h3 id="heading-map-transforming-elements">.map() - Transforming Elements</h3>
<p>The .map() method transforms each element in the iterator by applying a closure to it. The closure takes an element as input and returns a new value, which is then yielded by the iterator.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> numbers = [<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> squares: <span class="hljs-built_in">Vec</span>&lt;_&gt; = numbers.iter().map(|&amp;x| x * x).collect();
<span class="hljs-built_in">println!</span>(<span class="hljs-string">"Map - Squares: {:?}"</span>, squares); <span class="hljs-comment">// Outputs: [1, 4, 9, 16, 25]</span>
</code></pre>
<p>In this code, we use the .map() method to square each element in the numbers array. The closure |&amp;x| x * x squares the input x, and the resulting values are collected into a new vector.</p>
<h3 id="heading-filter-filtering-elements">.filter() - Filtering Elements</h3>
<p>The .filter() method filters elements in the iterator based on a predicate function. The closure takes an element as input and returns a boolean value indicating whether the element should be included in the output.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> numbers = [<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> evens: <span class="hljs-built_in">Vec</span>&lt;_&gt; = numbers.iter().filter(|&amp;x| x % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>).collect();

<span class="hljs-built_in">println!</span>(<span class="hljs-string">"Filter - Evens: {:?}"</span>, evens); <span class="hljs-comment">// Outputs: [2, 4]</span>
</code></pre>
<p>In this code, we use the .filter() method to select only the even numbers from the numbers array. The closure |&amp;x| x % 2 == 0 checks if the input x is even, and the resulting values are collected into a new vector.</p>
<h3 id="heading-fold-aggregating-elements">.fold() - Aggregating Elements</h3>
<p>The .fold() method aggregates elements in the iterator into a single value. It takes an initial value and a closure that combines the current accumulator value with each element in the iterator. It's similar to the reduce function in other languages.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> numbers = [<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> sum = numbers.iter().fold(<span class="hljs-number">0</span>, |acc, &amp;x| acc + x);

<span class="hljs-built_in">println!</span>(<span class="hljs-string">"Fold - Sum: {}"</span>, sum); <span class="hljs-comment">// Outputs: 15</span>
</code></pre>
<p>In this code, we use the .fold() method to calculate the sum of all elements in the numbers array. The initial value 0 is passed as the first argument, and the closure |acc, &amp;x| acc + x adds each element x to the accumulator acc.</p>
<h2 id="heading-summary">Summary</h2>
<p>Rust’s iterators provide a flexible way to process data efficiently by allowing transformations, filtering, and aggregations over collections. Key takeaways:</p>
<p>Laziness: Iterators do nothing until explicitly consumed.</p>
<p>Ownership and Mutability Control: Choose between iter(), iter_mut(), and into_iter() for precise control over element handling.</p>
<p>Functional Methods: Methods like .map(), .filter(), and .fold() allow expressive, functional transformations.</p>
<p>Iterators give fine-grained control over data ownership and mutability during iteration, making Rust efficient and powerful in processing collections.</p>
<p>If you prefer a video version:</p>
<iframe width="905" height="510" src="https://www.youtube.com/embed/Dtkv5i2nelk"></iframe>

<p>All the code is available on <a target="_blank" href="https://youtu.be/Dtkv5i2nelk">Github</a> (link in the video description)</p>
<p>You can find me here: https://francescociulla.com</p>
]]></content:encoded></item><item><title><![CDATA[Closures in Rust]]></title><description><![CDATA[In this lesson, we will introduce Closures in Rust, a flexible feature that allows functions to capture variables from their environment, making them highly useful for tasks like functional programming, callbacks, and lazy evaluation.
What Are Closur...]]></description><link>https://blog.francescociulla.com/closures-in-rust</link><guid isPermaLink="true">https://blog.francescociulla.com/closures-in-rust</guid><category><![CDATA[Rust]]></category><category><![CDATA[rust lang]]></category><category><![CDATA[Rust programming]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Sun, 06 Oct 2024 13:24:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728220906766/94b7cc02-d30f-464f-a53a-dd28b53e7cca.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this lesson, we will introduce <strong>Closures</strong> in Rust, a flexible feature that allows functions to capture variables from their environment, making them highly useful for tasks like functional programming, callbacks, and lazy evaluation.</p>
<h2 id="heading-what-are-closures">What Are Closures?</h2>
<p>Closures are blocks of code that can be assigned to variables, passed to other functions, or returned from functions. They are similar to regular functions, but closures have one key advantage: they can <strong>capture variables from the scope</strong> in which they are defined. This allows them to be more flexible and powerful than traditional functions.</p>
<p>If you prefer a video version:</p>
<iframe width="905" height="510" src="https://www.youtube.com/embed/agm_oW8t8tE"></iframe>

<p>All the code is available on <a target="_blank" href="https://youtu.be/agm_oW8t8tE">Github</a> (link in the video description)</p>
<h3 id="heading-key-characteristics-of-closures-in-rust">Key Characteristics of Closures in Rust:</h3>
<ul>
<li><strong>Anonymous Functions</strong>: Closures are unnamed functions that can be stored in variables or passed to other functions.</li>
<li><strong>Capturing Environment</strong>: Closures can capture values from their surrounding scope by borrowing, mutably borrowing, or taking ownership of them.</li>
<li><strong>Type Inference</strong>: Rust infers the types of parameters and return types in most closures, so explicit type annotations are often unnecessary.</li>
<li><strong>Flexibility</strong>: Closures can be stored as function pointers or as traits like <code>Fn</code>, <code>FnMut</code>, and <code>FnOnce</code>, depending on how they capture variables.</li>
</ul>
<h2 id="heading-syntax">Syntax</h2>
<p>Closures in Rust are defined using the <code>|args| body</code> syntax. The <code>args</code> represent the arguments the closure takes, and the <code>body</code> is the code that the closure executes. Here's an example of a closure that takes no arguments and returns a string:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> closure = || <span class="hljs-string">"Hello, world!"</span>;
</code></pre>
<p><a target="_blank" href="https://youtu.be/agm_oW8t8tE"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/brg9numuhl0matd42hzc.png" alt="Closures in Rust" /></a></p>
<p>Here's a more complex example with two arguments:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> closure = |a: <span class="hljs-built_in">i32</span>, b: <span class="hljs-built_in">i32</span>| -&gt; <span class="hljs-built_in">i32</span> {
    a + b
};
</code></pre>
<p>Rust can infer the types of a and b in most cases, so you can simplify this to:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> closure = |a, b| a + b;
</code></pre>
<h3 id="heading-example-simple-closure">Example: Simple Closure</h3>
<p>Here's an example of a closure that adds two numbers:</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> add = |a, b| a + b;
    <span class="hljs-keyword">let</span> result = add(<span class="hljs-number">3</span>, <span class="hljs-number">5</span>);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"The sum is: {}"</span>, result);
}
</code></pre>
<p><a target="_blank" href="https://youtu.be/agm_oW8t8tE"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j03p6f7tdoit97qr61x4.png" alt="Closures in Rust" /></a></p>
<p>In this example, the closure add takes two arguments, a and b, and returns their sum. The |a, b| syntax defines the closure's arguments, and the body is simply a + b.</p>
<h2 id="heading-capturing-variables-with-closures">Capturing Variables with Closures</h2>
<p>Closures can capture variables from their environment in three different ways: by borrowing (immutably or mutably) or by taking ownership of the variable (moving it). This behavior is determined by how the closure is used.</p>
<h3 id="heading-1-borrowing-immutable-capture">1. Borrowing (Immutable Capture)</h3>
<p>In this case, the closure borrows a variable immutably, meaning it can read the variable but not modify it.</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> x = <span class="hljs-number">5</span>;
    <span class="hljs-keyword">let</span> print_x = || {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"The value of x is: {}"</span>, x);
    };
    print_x();
}
</code></pre>
<p>In this example, the closure closure borrows the variable x immutably, allowing it to read x but not modify it.</p>
<p><a target="_blank" href="https://youtu.be/agm_oW8t8tE"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1nfzz0pylh0zrrkj20yz.png" alt="Closures in Rust" /></a></p>
<h3 id="heading-2-mutably-borrowing-mutable-capture">2. Mutably Borrowing (Mutable Capture)</h3>
<p>The closure borrows a variable mutably, allowing it to both read and modify the variable.</p>
<p>Example:</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> y = <span class="hljs-number">100</span>;
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> print_y = || {
        y += <span class="hljs-number">1</span>;
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"The value of x is: {}"</span>, y);
    };
    print_y();
}
</code></pre>
<p>In this example, the closure mutably borrows the variable x, allowing it to modify the value of x.</p>
<p><a target="_blank" href="https://youtu.be/agm_oW8t8tE"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v3l2bgeomdvw4x8h4w9d.png" alt="Closures in Rust" /></a></p>
<h3 id="heading-3-moving-ownership-capture">3. Moving (Ownership Capture)</h3>
<p>The closure can take ownership of a variable, meaning the variable is moved into the closure and can no longer be used outside of it.</p>
<p>Example:</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> x = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Hello"</span>);
    <span class="hljs-keyword">let</span> consume_x = <span class="hljs-keyword">move</span> || {  <span class="hljs-comment">// `x` is moved into the closure</span>
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Consumed: {}"</span>, x);
        <span class="hljs-built_in">drop</span>(x);  <span class="hljs-comment">// Consumes `x` by dropping it</span>
    };
    consume_x();  <span class="hljs-comment">// `x` is moved and consumed</span>
    <span class="hljs-comment">// consume_x();  // Error: closure can only be called once, `x` was consumed</span>
}
</code></pre>
<p>In this example, the closure consume_x takes ownership of the variable x by using the move keyword. After being moved into the closure, x cannot be used outside the closure.</p>
<p><a target="_blank" href="https://youtu.be/agm_oW8t8tE"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/95lew0gbzpaao48wwvh8.png" alt="Closures in Rust" /></a></p>
<h3 id="heading-closure-traits-fn-fnmut-and-fnonce">Closure Traits: Fn, FnMut, and FnOnce</h3>
<p>Rust provides three traits that represent how closures capture variables from their environment:</p>
<ul>
<li>Fn: The closure captures variables immutably, allowing it to be called multiple times.</li>
<li>FnMut: The closure captures variables mutably, meaning it can modify them. It can also be called multiple times.</li>
<li>FnOnce: The closure takes ownership of captured variables and can only be called once because it consumes the environment.</li>
</ul>
<p>Rust automatically chooses the most appropriate trait depending on how the closure is used.</p>
<h2 id="heading-closures-as-function-parameters">Closures as Function Parameters</h2>
<p>Closures can be passed as arguments to functions, enabling custom behavior within those functions.</p>
<p>This is often used in scenarios where you want to pass logic (in the form of a closure) to a function that can then execute it.</p>
<p>Example:</p>
<pre><code class="lang-rust"><span class="hljs-comment">// Fn trait bound: takes an i32 and returns an i32</span>
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">apply</span></span>&lt;F&gt;(f: F) <span class="hljs-keyword">where</span> F: <span class="hljs-built_in">Fn</span>(<span class="hljs-built_in">i32</span>) -&gt; <span class="hljs-built_in">i32</span>, {
    <span class="hljs-keyword">let</span> result = f(<span class="hljs-number">10</span>);  <span class="hljs-comment">// Call the closure with 10 as an argument</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Result: {}"</span>, result);
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> double = |x| x * <span class="hljs-number">2</span>;
    apply(double);  <span class="hljs-comment">// Pass the closure to a function</span>
}
</code></pre>
<p>In this example, the apply function accepts a closure f as an argument. </p>
<p>The closure must implement the Fn(i32) -&gt; i32 trait, which means it takes an i32 as input and returns an i32. </p>
<p>The double closure doubles its argument and is passed to apply, which calls it with the value 10.</p>
<p><a target="_blank" href="https://youtu.be/agm_oW8t8tE"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ypgdbq6ziyvuk2q1qwxg.png" alt="Closures in Rust" /></a></p>
<h2 id="heading-differences-between-functions-and-closures">Differences Between Functions and Closures</h2>
<p>While closures and functions share similarities, they have important differences:</p>
<ol>
<li><p>Capturing Variables: Closures can capture variables from the surrounding scope, whereas functions cannot.</p>
</li>
<li><p>Syntax: Closures are defined using the |args| body syntax, while functions use the fn keyword.</p>
</li>
<li><p>Flexibility: Closures can be stored in variables, passed around as arguments, and returned from other functions, giving them more flexibility than traditional functions.</p>
</li>
<li><p>Memory Usage: Closures that capture variables from their environment may use more memory than regular functions because they store those captured values.</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Closures in Rust are a powerful feature that allows you to capture variables from their environment and create flexible, reusable code blocks. By understanding the different ways closures capture variables (borrowing, mutably borrowing, or moving), you can make the most of Rust's closures in scenarios where traditional functions might fall short.</p>
<p>Closures are often used in functional programming, callback functions, and iterator chains, making them a vital part of mastering Rust.</p>
<p>If you prefer a video version:</p>
<iframe width="905" height="510" src="https://www.youtube.com/embed/agm_oW8t8tE"></iframe>

<p>All the code is available on <a target="_blank" href="https://youtu.be/agm_oW8t8tE">Github</a> (link in the video description)</p>
<p>All the code is available on <a target="_blank" href="https://youtu.be/agm_oW8t8tE">Github</a> (link in the video description)</p>
<p>If you have any comments, just drop them below.</p>
<p>You can also find me here: https://francescociulla.com</p>
]]></content:encoded></item><item><title><![CDATA[Environment Variables in Rust]]></title><description><![CDATA[Environment variables are a set of key-value pairs stored in the operating system. 
They are used to store configuration settings and other information required by the system and other applications. 
In this article, we'll explore how to work with en...]]></description><link>https://blog.francescociulla.com/environment-variables-in-rust</link><guid isPermaLink="true">https://blog.francescociulla.com/environment-variables-in-rust</guid><category><![CDATA[Rust]]></category><category><![CDATA[rust lang]]></category><category><![CDATA[Rust programming]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Sun, 22 Sep 2024 05:01:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1726981194843/4dc9d441-a253-47da-bdc0-4a6da04e995c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Environment variables are a set of key-value pairs stored in the operating system. </p>
<p>They are used to store configuration settings and other information required by the system and other applications. </p>
<p>In this article, we'll explore how to work with environment variables in Rust using the standard library and the <code>dotenv</code> crate.</p>
<h2 id="heading-what-are-environment-variables">What Are Environment Variables?</h2>
<p>Environment variables provide a flexible way to configure your applications without hardcoding values directly in your source code. </p>
<p>This makes it easier to manage different configurations for different environments, (development, testing, and production) and to keep sensitive information, such as API keys, secure.</p>
<p>Let's see 3 different examples of how we can use the environment variables in Rust.</p>
<ol>
<li>Using the <code>std::env</code> module</li>
<li>Using the command line (Windows and Linux)</li>
<li>Using the <code>dotenv</code> crate</li>
</ol>
<p>If you prefer a video version:</p>
<iframe width="905" height="510" src="https://www.youtube.com/embed/5mL3mFGQHM0 "></iframe>


<p>All the code is available on <a target="_blank" href="https://youtu.be/5mL3mFGQHM0">Github</a> (link in the video description)</p>
<h2 id="heading-1-environemnt-variables-using-the-stdenv-module">1. Environemnt Variables using the <code>std::env</code> module</h2>
<p>Rust provides the <code>std::env</code> module to interact with environment variables. This module can read, set, and remove environment variables.</p>
<h3 id="heading-importing-the-env-module">Importing the <code>env</code> Module</h3>
<p>First, import the <code>env</code> module from the standard library:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::env;
</code></pre>
<p>You can test this by typing <code>cargo run</code> in the terminal. </p>
<p>Your output should be something like this:</p>
<p><a target="_blank" href="https://youtu.be/5mL3mFGQHM0"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2teymua943zt4fm6ei2q.png" alt="Environment variables in Rust" /></a></p>
<h3 id="heading-setting-an-environment-variable">Setting an Environment Variable</h3>
<p>You can set an environment variable using the set_var function. Here's an example where we set a variable AAA with the value 123:</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> key = <span class="hljs-string">"AAA"</span>;
    std::env::set_var(key, <span class="hljs-string">"123"</span>); <span class="hljs-comment">// Sets AAA to 123</span>
}
</code></pre>
<h3 id="heading-removing-an-environment-variable">Removing an Environment Variable</h3>
<p>To remove an environment variable, use the remove_var function:</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> key = <span class="hljs-string">"AAA"</span>;
    env::remove_var(key); <span class="hljs-comment">// Removes the variable AAA</span>
}
</code></pre>
<h3 id="heading-checking-if-an-environment-variable-exists">Checking If an Environment Variable Exists</h3>
<p>To check if an environment variable exists, use the env::var function, which returns a Result. You can handle this with a match statement:</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> key = <span class="hljs-string">"AAA"</span>;

    <span class="hljs-keyword">match</span> env::var(key) {
        <span class="hljs-literal">Ok</span>(val) =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}: {:?}"</span>, key, val),
        <span class="hljs-literal">Err</span>(e) =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Error {}: {}"</span>, key, e),
    }
}
</code></pre>
<h3 id="heading-2-environment-variables-from-the-command-line">2. Environment Variables from the Command Line</h3>
<p>You can pass environment variables directly from the command line when running your Rust program:</p>
<p>Here's how you can read the CLI_ARG environment variable:</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> cli_arg = env::var(<span class="hljs-string">"CLI_ARG"</span>);

    <span class="hljs-keyword">match</span> cli_arg {
        <span class="hljs-literal">Ok</span>(val) =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"CLI_ARG: {:?}"</span>, val),
        <span class="hljs-literal">Err</span>(e) =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Error CLI_ARG: {}"</span>, e),
    }
}
</code></pre>
<p><a target="_blank" href="https://youtu.be/5mL3mFGQHM0"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mi0dm8n75kk4ukcvys3z.png" alt="Environment variables in Rust" /></a></p>
<p>To read them from the command line, you can use the following commands:</p>
<p>On Linux/macOS: </p>
<pre><code>CLI_ARG=TEST cargo run
</code></pre><p><a target="_blank" href="https://youtu.be/5mL3mFGQHM0"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3h768i4yyslf09vr9v89.png" alt="Environment variables in Rust" /></a></p>
<p>On Windows(powershell): </p>
<pre><code>$env:CLI_ARG=<span class="hljs-string">"TEST"</span>; cargo run
</code></pre><p><a target="_blank" href="https://youtu.be/5mL3mFGQHM0"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5s7lzhhba9utbvynujfy.png" alt="Environment variables in Rust" /></a></p>
<h2 id="heading-3-environment-variables-with-the-dotenv-crate">3. Environment Variables with the dotenv Crate</h2>
<p>In addition to the standard library, you can use the dotenv crate to load environment variables from a .env file. This is particularly useful in development environments.</p>
<p>First, add dotenv to your Cargo.toml file:</p>
<pre><code class="lang-toml"><span class="hljs-section">[dependencies]</span>
<span class="hljs-attr">dotenv</span> = <span class="hljs-string">"0.15.0"</span>
</code></pre>
<p>And create a .env file in the root of your project with the following content:</p>
<pre><code>API_KEY=<span class="hljs-number">1234567890</span>
</code></pre><h3 id="heading-loading-environment-variables-from-a-env-file">Loading Environment Variables from a .env File</h3>
<p>After adding dotenv, you can use it to load variables from a .env file:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> dotenv::dotenv;
<span class="hljs-keyword">use</span> std::env;

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    dotenv().ok(); <span class="hljs-comment">// Reads the .env file</span>

    <span class="hljs-keyword">let</span> api_key = env::var(<span class="hljs-string">"API_KEY"</span>);

    <span class="hljs-keyword">match</span> api_key {
        <span class="hljs-literal">Ok</span>(val) =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"API_KEY: {:?}"</span>, val),
        <span class="hljs-literal">Err</span>(e) =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Error API_KEY: {}"</span>, e),
    }

    <span class="hljs-comment">//Simulate the execution of the rest of the program</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"...program continues..."</span>);
}
</code></pre>
<p>And you if you run the program, you should see the output:</p>
<p><a target="_blank" href="https://youtu.be/5mL3mFGQHM0"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vf4wel6n7sd6o4cejyiy.png" alt="Environment variables in Rust" /></a></p>
<p>In the example above, the dotenv().ok(); line loads the variables from a .env file located in the root of your project. The program then attempts to read the API_KEY variable and prints its value or an error if it is not set.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>These are just three basic examples of working with environment variables in Rust. </p>
<p>I hope everything is clear and you can use them in your projects. If you have any questions, feel free to ask in the comments below.</p>
<p>If you prefer a video version:
If you prefer a video version:</p>
<iframe width="905" height="510" src="https://www.youtube.com/embed/5mL3mFGQHM0 "></iframe>



<p>All the code is available on <a target="_blank" href="https://youtu.be/5mL3mFGQHM0">Github</a> (link in the video description)</p>
<p>You can find me here: <a target="_blank" href="https://francescociulla.com">Francesco</a></p>
]]></content:encoded></item><item><title><![CDATA[Why might Rust be a smart choice for developers today?]]></title><description><![CDATA[Why might Rust be a smart choice for developers today?
Video Version


Rust was recently added to the Linux kernel, the first new language in nearly 30 years, endorsed by Linus Torvalds himself. It’s gaining traction for its focus on safety and relia...]]></description><link>https://blog.francescociulla.com/why-might-rust-be-a-smart-choice-for-developers-today</link><guid isPermaLink="true">https://blog.francescociulla.com/why-might-rust-be-a-smart-choice-for-developers-today</guid><category><![CDATA[Rust]]></category><category><![CDATA[rust lang]]></category><category><![CDATA[Rust programming]]></category><category><![CDATA[rustseries]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Sat, 21 Sep 2024 04:42:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1726893591413/27d21590-1753-48f3-86a3-a56213c52355.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Why might Rust be a smart choice for developers today?</p>
<p>Video Version</p>
<iframe width="905" height="510" src="https://www.youtube.com/embed/oiELnqVB8fM "></iframe>

<p>Rust was recently added to the Linux kernel, the first new language in nearly 30 years, endorsed by Linus Torvalds himself. It’s gaining traction for its focus on safety and reliability.</p>
<p>DARPA is backing Rust, aiming to convert millions of lines of C code to eliminate common security vulnerabilities.</p>
<p>Google reports that developers using Rust are twice as productive compared to C++. It's been crucial in reducing memory usage and defects in projects like Android.</p>
<p>Microsoft and Google have each invested $1 million in Rust's growth, showing confidence in its future.</p>
<p>Rust has been voted the most admired programming language by developers for many years in a row, even surpassing Kotlin in popularity and closing in on GO.</p>
<p>If you're considering a language that’s fast, safe, and gaining wide trust, Rust is worth a look.</p>
<p>Sources:
https://www.zdnet.com/article/rust-in-linux-where-we-are-and-where-were-going-next/
https://www.darkreading.com/application-security/darpa-aims-to-ditch-c-code-move-to-rust
https://survey.stackoverflow.co/2024/technology/
https://techinformed.com/world-in-disruption-trust-in-rust/
https://thenewstack.io/microsofts-1m-vote-of-confidence-in-rusts-future/
https://www.theregister.com/2024/02/05/google_rust_donation/</p>
<p>Video Version</p>
<iframe width="905" height="510" src="https://www.youtube.com/embed/oiELnqVB8fM "></iframe>]]></content:encoded></item><item><title><![CDATA[Rust fullstack web app! WASM + YEW + ROCKET]]></title><description><![CDATA[By the end of this tutorial, you will understand how to create a simple yet complete full-stack application using the following technologies:
For the Frontend:

Rust - Core Programming Language
Web Assembly - For running Rust in the browser
Yew - Rus...]]></description><link>https://blog.francescociulla.com/rust-fullstack-web-app-wasm-yew-rocket</link><guid isPermaLink="true">https://blog.francescociulla.com/rust-fullstack-web-app-wasm-yew-rocket</guid><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Rust]]></category><category><![CDATA[APIs]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Tue, 17 Sep 2024 14:37:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1726583771651/611f3f0d-3aed-4bd6-90bc-6842843d4ed0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>By the end of this tutorial, you will understand how to create a simple yet complete full-stack application using the following technologies:</p>
<p>For the Frontend:</p>
<ul>
<li>Rust - Core Programming Language</li>
<li>Web Assembly - For running Rust in the browser</li>
<li>Yew - Rust Framework for building client web apps</li>
<li>Trunk - For serving the frontend app</li>
<li>Tailwind CSS - For styling the frontend</li>
</ul>
<p>For the Backend:</p>
<ul>
<li>Rust - Core Programming Language</li>
<li>Rocket - Rust Framework for building web servers</li>
</ul>
<p>For the Database:</p>
<ul>
<li>Postgres - Relational Database</li>
<li>Docker - Dockerfile and Docker Compose for running Postgres</li>
</ul>
<p>Wow, so many technologies! But we'll keep the example as basic as possible to help you understand the core concepts. Let's get started! </p>
<p>We will proceed with a bottom-up approach, starting with the database, then the backend, and finally the frontend.  </p>
<p>If you prefer a video tutorial, you can watch it here.</p>
<iframe width="905" height="510" src="https://www.youtube.com/embed/D_76TcfzDTU "></iframe>


<p>All the code is available on <a target="_blank" href="https://youtu.be/FYVbt6YFMsM">GitHub</a> (link in video description)</p>
<h2 id="heading-architecture">Architecture</h2>
<p>Before we start, here is a simple architecture diagram of the application we are going to build:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xr096aqa4ffgo2yyob1k.png" alt="Build a rust fullstack web application" /></a></p>
<p>The front end will be built using Yew, a new Rust framework for building client web apps. Yew is inspired by Elm and React and is designed to be simple and easy to use. We will use Trunk to serve the frontend and Tailwind CSS for styling. All this will be compiled to Web Assembly and run in the browser.</p>
<p>The Backend will be built using Rocket, a web framework for Rust. Rocket is designed to maximize the Developer Experience. We will use Rocket to build a simple REST API that will interact with the database.</p>
<p>The Database will be Postgres, a relational database. We will use Docker to run Postgres in a container, and we will use no ORM to keep things simple. We will interact with the database using SQL queries written directly in the Rocket handlers.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before we start, make sure you have the following installed on your machine:</p>
<ul>
<li>Rust</li>
<li>Docker</li>
</ul>
<p>That's it! If you have never used WASM or Trunk, no worries; I will show you the commands you need to run.</p>
<h2 id="heading-preparation">Preparation.</h2>
<p>We will have a folder that will contain the following subfolders:</p>
<ul>
<li>backend</li>
<li>frontend</li>
</ul>
<p>So, let's create a new folder, navigate it, and open it in any IDE you want. </p>
<p>I will use Visual Studio Code.</p>
<pre><code class="lang-bash">mkdir rustfs
<span class="hljs-built_in">cd</span> rustfs
code .
</code></pre>
<p>From the root folder, initialize a git repository.</p>
<pre><code class="lang-bash">git init
</code></pre>
<p>And create a <code>compose.yml</code> file (this will be used to run the Postgres database)</p>
<p>And you should have something like this:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/36o8tyr23xu225gn6k33.png" alt="Build a rust fullstack web application" /></a></p>
<p>We are now ready to build our application. In the next section, we will set up the database.</p>
<h2 id="heading-setting-up-the-database">Setting up the Database</h2>
<p>We will use Docker to run a Postgres database in a container. This will make it easy to run the database locally without installing Postgres on your machine.</p>
<p>Open the <code>compose.yml</code> file and add the following:</p>
<pre><code class="lang-yml"><span class="hljs-attr">services:</span>
  <span class="hljs-attr">db:</span>
    <span class="hljs-attr">container_name:</span> <span class="hljs-string">db</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">postgres:12</span>
    <span class="hljs-attr">ports:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">"5432:5432"</span>
    <span class="hljs-attr">environment:</span>
      <span class="hljs-attr">POSTGRES_USER:</span> <span class="hljs-string">postgres</span>
      <span class="hljs-attr">POSTGRES_PASSWORD:</span> <span class="hljs-string">postgres</span>
      <span class="hljs-attr">POSTGRES_DB:</span> <span class="hljs-string">postgres</span>
    <span class="hljs-attr">volumes:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">pgdata:/var/lib/postgresql/data</span>

<span class="hljs-attr">volumes:</span>
  <span class="hljs-attr">pgdata:</span> {}
</code></pre>
<ul>
<li><code>db</code> is the name of the service</li>
<li><code>container_name</code> is the name of the container, we will use <code>db</code></li>
<li><code>image</code> is the Postgres image (we will use Postgres 12)</li>
<li><code>ports</code> is the port mapping (5432:5432)</li>
<li><code>environment</code> is the environment variables for the Postgres instance</li>
<li><code>volumes</code> is the volume mapping for the Postgres data</li>
</ul>
<p>We also define a volume <code>pgdata</code> that will be used to store the Postgres data.</p>
<p>Now, run the following command to start the Postgres database:</p>
<pre><code class="lang-bash">docker compose up
</code></pre>
<p>You should see the Postgres logs in the terminal. If you see <code>database system is ready to accept connections</code>, the database is probably running successfully.</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ibt7wgojoxi4w74sf1cx.png" alt="Build a rust fullstack web application" /></a></p>
<p>To make another test, you can go on the terminal and type:</p>
<pre><code class="lang-bash">docker ps -a
</code></pre>
<p>And you should see the database running:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rzj8nrrtu5oirc76hzd7.png" alt="Build a rust fullstack web application" /></a></p>
<p>You can also step into the database container by running:</p>
<pre><code class="lang-bash">docker <span class="hljs-built_in">exec</span> -it db psql -U postgres
</code></pre>
<p>You can check the current databases by running:</p>
<pre><code class="lang-bash">\dt
</code></pre>
<p>And you should see the following output (Did not find any relations):</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1asdk6dtkk68uv1kzty4.png" alt="Build a rust fullstack web application" /></a></p>
<p>This is because we have not created any tables yet. We will do that in the next section.</p>
<h2 id="heading-setting-up-the-backend">Setting up the Backend</h2>
<p>We will use Rocket to build the backend. </p>
<p>Rocket is a web framework for Rust that is designed to maximize the Developer Experience. We will use Rocket to build a simple REST API that will interact with the database.</p>
<p>Create a new Rust project called <code>backend</code>, without initializing a git repository:</p>
<pre><code class="lang-bash">cargo new backend --vcs none
</code></pre>
<p>Your project structure should look like this:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m2cqsucz9g9efrks3vgh.png" alt="Build a rust fullstack web application" /></a></p>
<p>Open the <code>Cargo.toml</code> file and add the following dependencies:</p>
<pre><code class="lang-toml"><span class="hljs-attr">rocket</span> = { version = <span class="hljs-string">"0.5"</span>, features = [<span class="hljs-string">"json"</span>] }
<span class="hljs-attr">serde</span> = { version = <span class="hljs-string">"1.0"</span>, features = [<span class="hljs-string">"derive"</span>] }
<span class="hljs-attr">serde_json</span> = <span class="hljs-string">"1.0"</span>
<span class="hljs-attr">tokio</span> = { version = <span class="hljs-string">"1"</span>, features = [<span class="hljs-string">"full"</span>] }
<span class="hljs-attr">tokio-postgres</span> = <span class="hljs-string">"0.7.11"</span>
<span class="hljs-attr">rocket_cors</span> = { version = <span class="hljs-string">"0.6.0"</span>, default-features = <span class="hljs-literal">false</span> }
</code></pre>
<ul>
<li><code>rocket</code> is the Rocket web framework we will use to build the backend</li>
<li><code>serde</code> is a serialization/deserialization library</li>
<li><code>serde_json</code> is a JSON serialization/deserialization library</li>
<li><code>tokio</code> is an asynchronous runtime for Rust</li>
<li><code>tokio-postgres</code> is a Postgres client for Tokio</li>
<li><code>rocket_cors</code> is a CORS library for Rocket</li>
</ul>
<p>Now, open the <code>/backend/main.rs</code> file and replace the contents with the following (explanation below):</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[macro_use]</span>
<span class="hljs-keyword">extern</span> <span class="hljs-keyword">crate</span> rocket;

<span class="hljs-keyword">use</span> rocket::serde::{ Deserialize, Serialize, json::Json };
<span class="hljs-keyword">use</span> rocket::{ State, response::status::Custom, http::Status };
<span class="hljs-keyword">use</span> tokio_postgres::{ Client, NoTls };
<span class="hljs-keyword">use</span> rocket_cors::{ CorsOptions, AllowedOrigins };

<span class="hljs-meta">#[derive(Serialize, Deserialize, Clone)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">User</span></span> {
    id: <span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">i32</span>&gt;,
    name: <span class="hljs-built_in">String</span>,
    email: <span class="hljs-built_in">String</span>,
}

<span class="hljs-meta">#[post(<span class="hljs-meta-string">"/api/users"</span>, data = <span class="hljs-meta-string">"&lt;user&gt;"</span>)]</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">add_user</span></span>(
    conn: &amp;State&lt;Client&gt;,
    user: Json&lt;User&gt;
) -&gt; <span class="hljs-built_in">Result</span>&lt;Json&lt;<span class="hljs-built_in">Vec</span>&lt;User&gt;&gt;, Custom&lt;<span class="hljs-built_in">String</span>&gt;&gt; {
    execute_query(
        conn,
        <span class="hljs-string">"INSERT INTO users (name, email) VALUES ($1, $2)"</span>,
        &amp;[&amp;user.name, &amp;user.email]
    ).<span class="hljs-keyword">await</span>?;
    get_users(conn).<span class="hljs-keyword">await</span>
}

<span class="hljs-meta">#[get(<span class="hljs-meta-string">"/api/users"</span>)]</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_users</span></span>(conn: &amp;State&lt;Client&gt;) -&gt; <span class="hljs-built_in">Result</span>&lt;Json&lt;<span class="hljs-built_in">Vec</span>&lt;User&gt;&gt;, Custom&lt;<span class="hljs-built_in">String</span>&gt;&gt; {
    get_users_from_db(conn).<span class="hljs-keyword">await</span>.map(Json)
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_users_from_db</span></span>(client: &amp;Client) -&gt; <span class="hljs-built_in">Result</span>&lt;<span class="hljs-built_in">Vec</span>&lt;User&gt;, Custom&lt;<span class="hljs-built_in">String</span>&gt;&gt; {
    <span class="hljs-keyword">let</span> users = client
        .query(<span class="hljs-string">"SELECT id, name, email FROM users"</span>, &amp;[]).<span class="hljs-keyword">await</span>
        .map_err(|e| Custom(Status::InternalServerError, e.to_string()))?
        .iter()
        .map(|row| User { id: <span class="hljs-literal">Some</span>(row.get(<span class="hljs-number">0</span>)), name: row.get(<span class="hljs-number">1</span>), email: row.get(<span class="hljs-number">2</span>) })
        .collect::&lt;<span class="hljs-built_in">Vec</span>&lt;User&gt;&gt;();

    <span class="hljs-literal">Ok</span>(users)
}

<span class="hljs-meta">#[put(<span class="hljs-meta-string">"/api/users/&lt;id&gt;"</span>, data = <span class="hljs-meta-string">"&lt;user&gt;"</span>)]</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">update_user</span></span>(
    conn: &amp;State&lt;Client&gt;,
    id: <span class="hljs-built_in">i32</span>,
    user: Json&lt;User&gt;
) -&gt; <span class="hljs-built_in">Result</span>&lt;Json&lt;<span class="hljs-built_in">Vec</span>&lt;User&gt;&gt;, Custom&lt;<span class="hljs-built_in">String</span>&gt;&gt; {
    execute_query(
        conn,
        <span class="hljs-string">"UPDATE users SET name = $1, email = $2 WHERE id = $3"</span>,
        &amp;[&amp;user.name, &amp;user.email, &amp;id]
    ).<span class="hljs-keyword">await</span>?;
    get_users(conn).<span class="hljs-keyword">await</span>
}

<span class="hljs-meta">#[delete(<span class="hljs-meta-string">"/api/users/&lt;id&gt;"</span>)]</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">delete_user</span></span>(conn: &amp;State&lt;Client&gt;, id: <span class="hljs-built_in">i32</span>) -&gt; <span class="hljs-built_in">Result</span>&lt;Status, Custom&lt;<span class="hljs-built_in">String</span>&gt;&gt; {
    execute_query(conn, <span class="hljs-string">"DELETE FROM users WHERE id = $1"</span>, &amp;[&amp;id]).<span class="hljs-keyword">await</span>?;
    <span class="hljs-literal">Ok</span>(Status::NoContent)
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">execute_query</span></span>(
    client: &amp;Client,
    query: &amp;<span class="hljs-built_in">str</span>,
    params: &amp;[&amp;(<span class="hljs-keyword">dyn</span> tokio_postgres::types::ToSql + <span class="hljs-built_in">Sync</span>)]
) -&gt; <span class="hljs-built_in">Result</span>&lt;<span class="hljs-built_in">u64</span>, Custom&lt;<span class="hljs-built_in">String</span>&gt;&gt; {
    client
        .execute(query, params).<span class="hljs-keyword">await</span>
        .map_err(|e| Custom(Status::InternalServerError, e.to_string()))
}

<span class="hljs-meta">#[launch]</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">rocket</span></span>() -&gt; _ {
    <span class="hljs-keyword">let</span> (client, connection) = tokio_postgres
        ::connect(<span class="hljs-string">"host=localhost user=postgres password=postgres dbname=postgres"</span>, NoTls).<span class="hljs-keyword">await</span>
        .expect(<span class="hljs-string">"Failed to connect to Postgres"</span>);

    tokio::spawn(<span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Err</span>(e) = connection.<span class="hljs-keyword">await</span> {
            eprintln!(<span class="hljs-string">"Failed to connect to Postgres: {}"</span>, e);
        }
    });

    <span class="hljs-comment">//Create the table if it doesn't exist</span>
    client
        .execute(
            <span class="hljs-string">"CREATE TABLE IF NOT EXISTS users (
                id SERIAL PRIMARY KEY,
                name TEXT NOT NULL,
                email TEXT NOT NULL
            )"</span>,
            &amp;[]
        ).<span class="hljs-keyword">await</span>
        .expect(<span class="hljs-string">"Failed to create table"</span>);

    <span class="hljs-keyword">let</span> cors = CorsOptions::default()
        .allowed_origins(AllowedOrigins::all())
        .to_cors()
        .expect(<span class="hljs-string">"Error while building CORS"</span>);

    rocket
        ::build()
        .manage(client)
        .mount(<span class="hljs-string">"/"</span>, routes![add_user, get_users, update_user, delete_user])
        .attach(cors)
}
</code></pre>
<p>In <a target="_blank" href="https://youtu.be/FYVbt6YFMsM?si=g62lZkqAroegr1lV">this part of the video</a>, I explain the code above.</p>
<p>Explanation</p>
<ul>
<li>We make all the imports at the top of the file. We also definte a <code>macro_use</code> attribute to import the <code>rocket</code> macro.</li>
<li>We define a <code>User</code> struct that will represent the user data. This struct will be serialized/deserialized to/from JSON (Note: The id is an <code>Option</code> because we don't want to provide an id when creating a new user, it will be assigned by the database).</li>
<li>We define the <code>add_user</code> route that will insert a new user into the database. We use the <code>execute_query</code> function to execute the SQL query. We then call the <code>get_users</code> function to return all the users.</li>
<li>We define the <code>get_users</code> route that will return all the users from the database.</li>
<li>We define the <code>update_user</code> route that will update a user in the database. We use the <code>execute_query</code> function to execute the SQL query. We then call the <code>get_users</code> function to return all the users.</li>
<li>We define the <code>delete_user</code> route that will delete a user from the database. We use the <code>execute_query</code> function to execute the SQL query.</li>
<li>We define the <code>execute_query</code> function that will execute a SQL query on the database.</li>
<li>We define the <code>rocket</code> function that will create the Rocket instance. We connect to the Postgres database and create the <code>users</code> table if it doesn't exist, using a SQL query. We then create the CORS options and attach them to the Rocket instance. Even if we are running the frontend and back end on the same machine, we need to enable CORS to allow the frontend to make requests to the backend.</li>
</ul>
<p>We can now run the backend by running:</p>
<pre><code class="lang-bash">cargo run
</code></pre>
<p>And we should see the following output:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ef3f3w5yeigwsc3ctba.png" alt="Build a rust fullstack web application" /></a></p>
<p>You can visit the following URL: <code>http://127.0.0.1:8000/api/users</code> and you should see an empty array <code>[]</code>:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lctpm4ic0ci0x1fdzteg.png" alt="Build a rust fullstack web application" /></a></p>
<h3 id="heading-testing-the-apis-with-postman">Testing the APIs with Postman</h3>
<p>You can test the APIs using Postman. </p>
<p>You can get the list of the users by sending a <code>GET</code> request to <code>http://127.0.0.1:8000/api/users</code>:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r36hk2f89xgnta8zxykx.png" alt="Build a rust fullstack web application" /></a></p>
<p>You can create a new user by sending a <code>POST</code> request to <code>http://127.0.0.1:8000/api/users</code> with the following JSON body:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"AAA"</span>,
    <span class="hljs-attr">"email"</span>: <span class="hljs-string">"aaa@mail.com"</span>
}
</code></pre>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/er9ex1e6ih0r9rwh45qm.png" alt="Build a rust fullstack web application" /></a></p>
<p>You can create 2 more users:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"BBB"</span>,
    <span class="hljs-attr">"email"</span>: <span class="hljs-string">"
}</span>
</code></pre>
<pre><code class="lang-json">{
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"CCC"</span>,
    <span class="hljs-attr">"email"</span>: <span class="hljs-string">"
}</span>
</code></pre>
<p>You should see the following output:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bjecymzisay9noeh8nba.png" alt="Build a rust fullstack web application" /></a></p>
<p>To Update a user, you can send a <code>PUT</code> request to <code>http://127.0.0.1:8000/api/users/2</code> with the following JSON body:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Francesco"</span>,
    <span class="hljs-attr">"email"</span>: <span class="hljs-string">"francesco@mail"</span>
}
</code></pre>
<p>And we should see the updated user:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ybo563f6wszq7uj5w1sj.png" alt="Build a rust fullstack web application" /></a></p>
<p>To delete a user, you can send a <code>DELETE</code> request to <code>http://127.0.0.1:8000/api/users/1</code>:</p>
<p>And we should get a 204 response (Resource was deleted):</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yp3uf9afnj37gqal5mn1.png" alt="Build a rust fullstack web application" /></a> </p>
<p>And if we try to get all the users, we should see the following output:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mq8jkod0h9i4i0u1uj6r.png" alt="Build a rust fullstack web application" /></a></p>
<p>We can see that this is consistent if we use the browser to check the users at the address <code>http://127.0.0.1:8000/api/users</code>:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7u7ynlld3vi9umw4mh28.png" alt="Build a rust fullstack web application" /></a></p>
<p>We can also test it directly in the Postgres database by running:
(If you closed the terminal, you can step into the container by running <code>docker exec -it db psql -U postgres</code>)</p>
<pre><code class="lang-bash">\dt
select * from users;
</code></pre>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tlf5dt0ik42dkf67mgdl.png" alt="Build a rust fullstack web application" /></a></p>
<p>Congratulations! You have successfully set up the backend. In the next section, we will set up the frontend.</p>
<h2 id="heading-setting-up-the-frontend">Setting up the Frontend</h2>
<p>Now, let's work on the front end. We will use Yew to build it. Yew is a Rust framework for building client web apps. We will use Trunk to build and bundle the front end and Tailwind CSS for styling. All this will be compiled to Web Assembly and run in the browser.</p>
<p><strong>IMPORTANT!</strong> If you never used Wasm for Rust on your machine, you can install it by running:</p>
<pre><code class="lang-bash">rustup target add wasm32-unknown-unknown
</code></pre>
<p><strong>IMPORTANT!</strong> You must also have <code>trunk</code> installed on your machine. You can install it by running:</p>
<pre><code class="lang-bash">cargo install trunk
</code></pre>
<p>You can verify that <code>trunk</code> is installed by running:</p>
<pre><code class="lang-bash">trunk --version
</code></pre>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ec96sei8ndvz5ivepsp.png" alt="Build a rust fullstack web application" /></a></p>
<p>Now you can create a new Rust project called <code>frontend</code> (be sure to be in the <code>rustfs</code> folder):</p>
<pre><code class="lang-bash">cargo new frontend --vcs none
</code></pre>
<p>Now open the <code>frontend/Cargo.toml</code> file and add the following dependencies:</p>
<pre><code class="lang-toml"><span class="hljs-section">[package]</span>
<span class="hljs-attr">name</span> = <span class="hljs-string">"frontend"</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">"2021"</span>

<span class="hljs-section">[dependencies]</span>
<span class="hljs-attr">yew</span> = { version = <span class="hljs-string">"0.21"</span>, features = [<span class="hljs-string">"csr"</span>] }
<span class="hljs-attr">wasm-bindgen</span> = <span class="hljs-string">"0.2"</span>
<span class="hljs-attr">web-sys</span> = { version = <span class="hljs-string">"0.3"</span>, features = [<span class="hljs-string">"console"</span>] }
<span class="hljs-attr">gloo</span> = <span class="hljs-string">"0.6"</span>
<span class="hljs-attr">wasm-bindgen-futures</span> = <span class="hljs-string">"0.4"</span>  
<span class="hljs-attr">serde</span> = { version = <span class="hljs-string">"1.0"</span>, features = [<span class="hljs-string">"derive"</span>] }
<span class="hljs-attr">serde_json</span> = <span class="hljs-string">"1.0"</span>
</code></pre>
<ul>
<li><code>yew</code> is the Yew framework (Rust framework for building client web apps)</li>
<li><code>wasm-bindgen</code> is a library that facilitates communication between WebAssembly and JavaScript</li>
<li><code>web-sys</code> is a library that provides bindings to Web APIs</li>
<li><code>gloo</code> is a library that provides utilities for WebAssembly</li>
<li><code>wasm-bindgen-futures</code> is a library that provides utilities for working with futures in WebAssembly</li>
<li><code>serde</code> is a serialization/deserialization library</li>
<li><code>serde_json</code> is a JSON serialization/deserialization library</li>
</ul>
<p>Now create a new file called <code>index.html</code> in the <code>frontend</code> folder and add the following:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Yew + Tailwind<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://cdn.tailwindcss.com"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"app"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">import</span> init <span class="hljs-keyword">from</span> <span class="hljs-string">'./pkg/frontend.js'</span>;
      init();
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<ul>
<li>We import the Tailwind CSS CDN in the head of the HTML file</li>
<li>We create a div with the id <code>app</code> where the Yew app will be mounted</li>
<li>We import the <code>frontend.js</code> file that will be generated by Trunk</li>
</ul>
<p>Now open the <code>frontend/src/main.rs</code> file and replace the contents with the following:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> yew::prelude::*;
<span class="hljs-keyword">use</span> serde::{ Deserialize, Serialize };
<span class="hljs-keyword">use</span> gloo::net::http::Request;
<span class="hljs-keyword">use</span> wasm_bindgen_futures::spawn_local;

<span class="hljs-meta">#[derive(Serialize, Deserialize, Clone, Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">User</span></span> {
    id: <span class="hljs-built_in">i32</span>,
    name: <span class="hljs-built_in">String</span>,
    email: <span class="hljs-built_in">String</span>,
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    yew::Renderer::&lt;App&gt;::new().render();
}
</code></pre>
<ul>
<li>We import the necessary dependencies</li>
<li>We define a <code>User</code> struct that will represent the user data</li>
<li>We define the <code>main</code> function that will render the Yew app</li>
</ul>
<p>But this is not enough. We need to add the <code>App</code> component. We can use an external file, but here for simplicity, we will add it directly in the <code>main.rs</code> file.</p>
<p>Below is the code you should add to the main.rs file.</p>
<p>This code defines a Yew function component named App that manages user data and interactions within a web application. The use_state hooks initialize states for managing user information <code>(user_state)</code>, messages <code>(message)</code>, and the list of users <code>(users)</code>. </p>
<p>The component defines several callbacks for interacting with a backend API:</p>
<ul>
<li><code>get_users:</code> Fetches the list of users from the backend API and updates the users state. If the request fails, it sets an error message.</li>
<li><code>create_user:</code> Sends a POST request to create a new user using the data from user_state. On success, it triggers the get_users callback to refresh the user list.</li>
<li><code>update_user:</code> Updates an existing user's information by sending a PUT request to the backend. If successful, it refreshes the user list and resets the user_state.</li>
<li><code>delete_user:</code> Deletes a user based on their ID by sending a DELETE request to the backend. On success, it refreshes the user list.</li>
<li><code>edit_user:</code> Prepares a user's information for editing by updating the user_state with the selected user's details.</li>
</ul>
<p>These callbacks utilize asynchronous operations <code>(spawn_local)</code> to handle network requests without blocking the UI thread, ensuring a responsive user experience.</p>
<pre><code class="lang-rust">...
<span class="hljs-meta">#[function_component(App)]</span>
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">app</span></span>() -&gt; Html {
    <span class="hljs-keyword">let</span> user_state = use_state(|| (<span class="hljs-string">""</span>.to_string(), <span class="hljs-string">""</span>.to_string(), <span class="hljs-literal">None</span> <span class="hljs-keyword">as</span> <span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">i32</span>&gt;));
    <span class="hljs-keyword">let</span> message = use_state(|| <span class="hljs-string">""</span>.to_string());
    <span class="hljs-keyword">let</span> users = use_state(<span class="hljs-built_in">Vec</span>::new);

    <span class="hljs-keyword">let</span> get_users = {
        <span class="hljs-keyword">let</span> users = users.clone();
        <span class="hljs-keyword">let</span> message = message.clone();
        Callback::from(<span class="hljs-keyword">move</span> |_| {
            <span class="hljs-keyword">let</span> users = users.clone();
            <span class="hljs-keyword">let</span> message = message.clone();
            spawn_local(<span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
                <span class="hljs-keyword">match</span> Request::get(<span class="hljs-string">"http://127.0.0.1:8000/api/users"</span>).send().<span class="hljs-keyword">await</span> {
                    <span class="hljs-literal">Ok</span>(resp) <span class="hljs-keyword">if</span> resp.ok() =&gt; {
                        <span class="hljs-keyword">let</span> fetched_users: <span class="hljs-built_in">Vec</span>&lt;User&gt; = resp.json().<span class="hljs-keyword">await</span>.unwrap_or_default();
                        users.set(fetched_users);
                    }

                    _ =&gt; message.set(<span class="hljs-string">"Failed to fetch users"</span>.into()),
                }
            });
        })
    };

    <span class="hljs-keyword">let</span> create_user = {
        <span class="hljs-keyword">let</span> user_state = user_state.clone();
        <span class="hljs-keyword">let</span> message = message.clone();
        <span class="hljs-keyword">let</span> get_users = get_users.clone();
        Callback::from(<span class="hljs-keyword">move</span> |_| {
            <span class="hljs-keyword">let</span> (name, email, _) = (*user_state).clone();
            <span class="hljs-keyword">let</span> user_state = user_state.clone();
            <span class="hljs-keyword">let</span> message = message.clone();
            <span class="hljs-keyword">let</span> get_users = get_users.clone();

            spawn_local(<span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
                <span class="hljs-keyword">let</span> user_data = serde_json::json!({ <span class="hljs-string">"name"</span>: name, <span class="hljs-string">"email"</span>: email });

                <span class="hljs-keyword">let</span> response = Request::post(<span class="hljs-string">"http://127.0.0.1:8000/api/users"</span>)
                    .header(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>)
                    .body(user_data.to_string())
                    .send().<span class="hljs-keyword">await</span>;

                <span class="hljs-keyword">match</span> response {
                    <span class="hljs-literal">Ok</span>(resp) <span class="hljs-keyword">if</span> resp.ok() =&gt; {
                        message.set(<span class="hljs-string">"User created successfully"</span>.into());
                        get_users.emit(());
                    }

                    _ =&gt; message.set(<span class="hljs-string">"Failed to create user"</span>.into()),
                }

                user_state.set((<span class="hljs-string">""</span>.to_string(), <span class="hljs-string">""</span>.to_string(), <span class="hljs-literal">None</span>));
            });
        })
    };

    <span class="hljs-keyword">let</span> update_user = {
        <span class="hljs-keyword">let</span> user_state = user_state.clone();
        <span class="hljs-keyword">let</span> message = message.clone();
        <span class="hljs-keyword">let</span> get_users = get_users.clone();

        Callback::from(<span class="hljs-keyword">move</span> |_| {
            <span class="hljs-keyword">let</span> (name, email, editing_user_id) = (*user_state).clone();
            <span class="hljs-keyword">let</span> user_state = user_state.clone();
            <span class="hljs-keyword">let</span> message = message.clone();
            <span class="hljs-keyword">let</span> get_users = get_users.clone();

            <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Some</span>(id) = editing_user_id {
                spawn_local(<span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
                    <span class="hljs-keyword">let</span> response = Request::put(&amp;<span class="hljs-built_in">format!</span>(<span class="hljs-string">"http://127.0.0.1:8000/api/users/{}"</span>, id))
                        .header(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>)
                        .body(serde_json::to_string(&amp;(id, name.as_str(), email.as_str())).unwrap())
                        .send().<span class="hljs-keyword">await</span>;

                    <span class="hljs-keyword">match</span> response {
                        <span class="hljs-literal">Ok</span>(resp) <span class="hljs-keyword">if</span> resp.ok() =&gt; {
                            message.set(<span class="hljs-string">"User updated successfully"</span>.into());
                            get_users.emit(());
                        }

                        _ =&gt; message.set(<span class="hljs-string">"Failed to update user"</span>.into()),
                    }

                    user_state.set((<span class="hljs-string">""</span>.to_string(), <span class="hljs-string">""</span>.to_string(), <span class="hljs-literal">None</span>));
                });
            }
        })
    };

    <span class="hljs-keyword">let</span> delete_user = {
        <span class="hljs-keyword">let</span> message = message.clone();
        <span class="hljs-keyword">let</span> get_users = get_users.clone();

        Callback::from(<span class="hljs-keyword">move</span> |id: <span class="hljs-built_in">i32</span>| {
            <span class="hljs-keyword">let</span> message = message.clone();
            <span class="hljs-keyword">let</span> get_users = get_users.clone();

            spawn_local(<span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
                <span class="hljs-keyword">let</span> response = Request::delete(
                    &amp;<span class="hljs-built_in">format!</span>(<span class="hljs-string">"http://127.0.0.1:8000/api/users/{}"</span>, id)
                ).send().<span class="hljs-keyword">await</span>;

                <span class="hljs-keyword">match</span> response {
                    <span class="hljs-literal">Ok</span>(resp) <span class="hljs-keyword">if</span> resp.ok() =&gt; {
                        message.set(<span class="hljs-string">"User deleted successfully"</span>.into());
                        get_users.emit(());
                    }

                    _ =&gt; message.set(<span class="hljs-string">"Failed to delete user"</span>.into()),
                }
            });
        })
    };

    <span class="hljs-keyword">let</span> edit_user = {
        <span class="hljs-keyword">let</span> user_state = user_state.clone();
        <span class="hljs-keyword">let</span> users = users.clone();

        Callback::from(<span class="hljs-keyword">move</span> |id: <span class="hljs-built_in">i32</span>| {
            <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Some</span>(user) = users.iter().find(|u| u.id == id) {
                user_state.set((user.name.clone(), user.email.clone(), <span class="hljs-literal">Some</span>(id)));
            }
        })
    };
...
</code></pre>
<p>You can check writing the code line by line in <a target="_blank" href="https://youtu.be/FYVbt6YFMsM?si=TtWTrFM4Rf6bbhNL">this part of the video</a></p>
<p>Now we need to add the HTML code rendered by the Yew component. Below is the code you should add in the main.rs file.</p>
<p>If you know React, this is similar to what happens in a JSX file.</p>
<p>This HTML part written using Yew's html! macro, defines the user interface of the Yew application. It consists of several key sections that provide functionalities for managing users.</p>
<ul>
<li>A main container with some padding and a nice layout using Tailwind CSS.</li>
<li>A big title at the top says “User Management” to let users know what the app is about.</li>
<li>Two input fields: one for the user's name and another for their email. As you type, it updates the state to track what’s entered.</li>
<li>A button that changes its action and label depending on whether you're creating a new user or updating an existing one. It says <code>Create User</code> if you're adding a new one or <code>Update User</code> if you're editing.</li>
<li>A space for messages to appear—like success or error messages—just below the input fields (the text color is always green; feel free to make it red in case of errors).</li>
<li>A <code>Fetch User List</code> button that, when clicked, pulls the latest user data from the backend.</li>
<li>A section that lists all the users fetched from the backend, showing their ID, name, and email.</li>
<li>Each user in the list has a "Delete" button to remove them and an "Edit" button to load their details into the input fields for editing.</li>
</ul>
<pre><code class="lang-rust">...
html! {
        &lt;div class=<span class="hljs-string">"container mx-auto p-4"</span>&gt;
            &lt;h1 class=<span class="hljs-string">"text-4xl font-bold text-blue-500 mb-4"</span>&gt;{ <span class="hljs-string">"User Management"</span> }&lt;/h1&gt;
                &lt;div class=<span class="hljs-string">"mb-4"</span>&gt;
                    &lt;input
                        placeholder=<span class="hljs-string">"Name"</span>
                        value={user_state.<span class="hljs-number">0</span>.clone()}
                        oninput={Callback::from({
                            <span class="hljs-keyword">let</span> user_state = user_state.clone();
                            <span class="hljs-keyword">move</span> |e: InputEvent| {
                                <span class="hljs-keyword">let</span> input = e.target_dyn_into::&lt;web_sys::HtmlInputElement&gt;().unwrap();
                                user_state.set((input.value(), user_state.<span class="hljs-number">1</span>.clone(), user_state.<span class="hljs-number">2</span>));
                            }
                        })}
                        class=<span class="hljs-string">"border rounded px-4 py-2 mr-2"</span>
                    /&gt;
                    &lt;input
                        placeholder=<span class="hljs-string">"Email"</span>
                        value={user_state.<span class="hljs-number">1</span>.clone()}
                        oninput={Callback::from({
                            <span class="hljs-keyword">let</span> user_state = user_state.clone();
                            <span class="hljs-keyword">move</span> |e: InputEvent| {
                                <span class="hljs-keyword">let</span> input = e.target_dyn_into::&lt;web_sys::HtmlInputElement&gt;().unwrap();
                                user_state.set((user_state.<span class="hljs-number">0</span>.clone(), input.value(), user_state.<span class="hljs-number">2</span>));
                            }
                        })}
                        class=<span class="hljs-string">"border rounded px-4 py-2 mr-2"</span>
                    /&gt;

                    &lt;button
                        onclick={<span class="hljs-keyword">if</span> user_state.<span class="hljs-number">2</span>.is_some() { update_user.clone() } <span class="hljs-keyword">else</span> { create_user.clone() }}
                        class=<span class="hljs-string">"bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"</span>
                    &gt;
                        { <span class="hljs-keyword">if</span> user_state.<span class="hljs-number">2</span>.is_some() { <span class="hljs-string">"Update User"</span> } <span class="hljs-keyword">else</span> { <span class="hljs-string">"Create User"</span> } }

                    &lt;/button&gt;
                        <span class="hljs-keyword">if</span> !message.is_empty() {
                        &lt;p class=<span class="hljs-string">"text-green-500 mt-2"</span>&gt;{ &amp;*message }&lt;/p&gt;
                    }
                &lt;/div&gt;

                &lt;button
                    onclick={get_users.reform(|_| ())}  
                    class=<span class="hljs-string">"bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded mb-4"</span>
                &gt;
                    { <span class="hljs-string">"Fetch User List"</span> }
                &lt;/button&gt;

                &lt;h2 class=<span class="hljs-string">"text-2xl font-bold text-gray-700 mb-2"</span>&gt;{ <span class="hljs-string">"User List"</span> }&lt;/h2&gt;

                &lt;ul class=<span class="hljs-string">"list-disc pl-5"</span>&gt;
                    { <span class="hljs-keyword">for</span> (*users).iter().map(|user| {
                        <span class="hljs-keyword">let</span> user_id = user.id;
                        html! {
                            &lt;li class=<span class="hljs-string">"mb-2"</span>&gt;
                                &lt;span class=<span class="hljs-string">"font-semibold"</span>&gt;{ <span class="hljs-built_in">format!</span>(<span class="hljs-string">"ID: {}, Name: {}, Email: {}"</span>, user.id, user.name, user.email) }&lt;/span&gt;
                                &lt;button
                                    onclick={delete_user.clone().reform(<span class="hljs-keyword">move</span> |_| user_id)}
                                    class=<span class="hljs-string">"ml-4 bg-red-500 hover:bg-red-700 text-white font-bold py-1 px-2 rounded"</span>
                                &gt;
                                    { <span class="hljs-string">"Delete"</span> }
                                &lt;/button&gt;
                                &lt;button
                                    onclick={edit_user.clone().reform(<span class="hljs-keyword">move</span> |_| user_id)}
                                    class=<span class="hljs-string">"ml-4 bg-yellow-500 hover:bg-yellow-700 text-white font-bold py-1 px-2 rounded"</span>
                                &gt;
                                    { <span class="hljs-string">"Edit"</span> }
                                &lt;/button&gt;
                            &lt;/li&gt;
                        }
                    })}

                &lt;/ul&gt;


        &lt;/div&gt;
    }
...
</code></pre>
<p>You can check writing the code line by line in this part of the video</p>
<p>Here is the complete code for the <code>/frontend/src/main.rs</code> file:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> yew::prelude::*;
<span class="hljs-keyword">use</span> serde::{ Deserialize, Serialize };
<span class="hljs-keyword">use</span> gloo::net::http::Request;
<span class="hljs-keyword">use</span> wasm_bindgen_futures::spawn_local;

<span class="hljs-meta">#[function_component(App)]</span>
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">app</span></span>() -&gt; Html {
    <span class="hljs-keyword">let</span> user_state = use_state(|| (<span class="hljs-string">""</span>.to_string(), <span class="hljs-string">""</span>.to_string(), <span class="hljs-literal">None</span> <span class="hljs-keyword">as</span> <span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">i32</span>&gt;));
    <span class="hljs-keyword">let</span> message = use_state(|| <span class="hljs-string">""</span>.to_string());
    <span class="hljs-keyword">let</span> users = use_state(<span class="hljs-built_in">Vec</span>::new);

    <span class="hljs-keyword">let</span> get_users = {
        <span class="hljs-keyword">let</span> users = users.clone();
        <span class="hljs-keyword">let</span> message = message.clone();
        Callback::from(<span class="hljs-keyword">move</span> |_| {
            <span class="hljs-keyword">let</span> users = users.clone();
            <span class="hljs-keyword">let</span> message = message.clone();
            spawn_local(<span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
                <span class="hljs-keyword">match</span> Request::get(<span class="hljs-string">"http://127.0.0.1:8000/api/users"</span>).send().<span class="hljs-keyword">await</span> {
                    <span class="hljs-literal">Ok</span>(resp) <span class="hljs-keyword">if</span> resp.ok() =&gt; {
                        <span class="hljs-keyword">let</span> fetched_users: <span class="hljs-built_in">Vec</span>&lt;User&gt; = resp.json().<span class="hljs-keyword">await</span>.unwrap_or_default();
                        users.set(fetched_users);
                    }

                    _ =&gt; message.set(<span class="hljs-string">"Failed to fetch users"</span>.into()),
                }
            });
        })
    };

    <span class="hljs-keyword">let</span> create_user = {
        <span class="hljs-keyword">let</span> user_state = user_state.clone();
        <span class="hljs-keyword">let</span> message = message.clone();
        <span class="hljs-keyword">let</span> get_users = get_users.clone();
        Callback::from(<span class="hljs-keyword">move</span> |_| {
            <span class="hljs-keyword">let</span> (name, email, _) = (*user_state).clone();
            <span class="hljs-keyword">let</span> user_state = user_state.clone();
            <span class="hljs-keyword">let</span> message = message.clone();
            <span class="hljs-keyword">let</span> get_users = get_users.clone();

            spawn_local(<span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
                <span class="hljs-keyword">let</span> user_data = serde_json::json!({ <span class="hljs-string">"name"</span>: name, <span class="hljs-string">"email"</span>: email });

                <span class="hljs-keyword">let</span> response = Request::post(<span class="hljs-string">"http://127.0.0.1:8000/api/users"</span>)
                    .header(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>)
                    .body(user_data.to_string())
                    .send().<span class="hljs-keyword">await</span>;

                <span class="hljs-keyword">match</span> response {
                    <span class="hljs-literal">Ok</span>(resp) <span class="hljs-keyword">if</span> resp.ok() =&gt; {
                        message.set(<span class="hljs-string">"User created successfully"</span>.into());
                        get_users.emit(());
                    }

                    _ =&gt; message.set(<span class="hljs-string">"Failed to create user"</span>.into()),
                }

                user_state.set((<span class="hljs-string">""</span>.to_string(), <span class="hljs-string">""</span>.to_string(), <span class="hljs-literal">None</span>));
            });
        })
    };

    <span class="hljs-keyword">let</span> update_user = {
        <span class="hljs-keyword">let</span> user_state = user_state.clone();
        <span class="hljs-keyword">let</span> message = message.clone();
        <span class="hljs-keyword">let</span> get_users = get_users.clone();

        Callback::from(<span class="hljs-keyword">move</span> |_| {
            <span class="hljs-keyword">let</span> (name, email, editing_user_id) = (*user_state).clone();
            <span class="hljs-keyword">let</span> user_state = user_state.clone();
            <span class="hljs-keyword">let</span> message = message.clone();
            <span class="hljs-keyword">let</span> get_users = get_users.clone();

            <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Some</span>(id) = editing_user_id {
                spawn_local(<span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
                    <span class="hljs-keyword">let</span> response = Request::put(&amp;<span class="hljs-built_in">format!</span>(<span class="hljs-string">"http://127.0.0.1:8000/api/users/{}"</span>, id))
                        .header(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>)
                        .body(serde_json::to_string(&amp;(id, name.as_str(), email.as_str())).unwrap())
                        .send().<span class="hljs-keyword">await</span>;

                    <span class="hljs-keyword">match</span> response {
                        <span class="hljs-literal">Ok</span>(resp) <span class="hljs-keyword">if</span> resp.ok() =&gt; {
                            message.set(<span class="hljs-string">"User updated successfully"</span>.into());
                            get_users.emit(());
                        }

                        _ =&gt; message.set(<span class="hljs-string">"Failed to update user"</span>.into()),
                    }

                    user_state.set((<span class="hljs-string">""</span>.to_string(), <span class="hljs-string">""</span>.to_string(), <span class="hljs-literal">None</span>));
                });
            }
        })
    };

    <span class="hljs-keyword">let</span> delete_user = {
        <span class="hljs-keyword">let</span> message = message.clone();
        <span class="hljs-keyword">let</span> get_users = get_users.clone();

        Callback::from(<span class="hljs-keyword">move</span> |id: <span class="hljs-built_in">i32</span>| {
            <span class="hljs-keyword">let</span> message = message.clone();
            <span class="hljs-keyword">let</span> get_users = get_users.clone();

            spawn_local(<span class="hljs-keyword">async</span> <span class="hljs-keyword">move</span> {
                <span class="hljs-keyword">let</span> response = Request::delete(
                    &amp;<span class="hljs-built_in">format!</span>(<span class="hljs-string">"http://127.0.0.1:8000/api/users/{}"</span>, id)
                ).send().<span class="hljs-keyword">await</span>;

                <span class="hljs-keyword">match</span> response {
                    <span class="hljs-literal">Ok</span>(resp) <span class="hljs-keyword">if</span> resp.ok() =&gt; {
                        message.set(<span class="hljs-string">"User deleted successfully"</span>.into());
                        get_users.emit(());
                    }

                    _ =&gt; message.set(<span class="hljs-string">"Failed to delete user"</span>.into()),
                }
            });
        })
    };

    <span class="hljs-keyword">let</span> edit_user = {
        <span class="hljs-keyword">let</span> user_state = user_state.clone();
        <span class="hljs-keyword">let</span> users = users.clone();

        Callback::from(<span class="hljs-keyword">move</span> |id: <span class="hljs-built_in">i32</span>| {
            <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Some</span>(user) = users.iter().find(|u| u.id == id) {
                user_state.set((user.name.clone(), user.email.clone(), <span class="hljs-literal">Some</span>(id)));
            }
        })
    };

    <span class="hljs-comment">//html</span>

    html! {
        &lt;div class=<span class="hljs-string">"container mx-auto p-4"</span>&gt;
            &lt;h1 class=<span class="hljs-string">"text-4xl font-bold text-blue-500 mb-4"</span>&gt;{ <span class="hljs-string">"User Management"</span> }&lt;/h1&gt;
                &lt;div class=<span class="hljs-string">"mb-4"</span>&gt;
                    &lt;input
                        placeholder=<span class="hljs-string">"Name"</span>
                        value={user_state.<span class="hljs-number">0</span>.clone()}
                        oninput={Callback::from({
                            <span class="hljs-keyword">let</span> user_state = user_state.clone();
                            <span class="hljs-keyword">move</span> |e: InputEvent| {
                                <span class="hljs-keyword">let</span> input = e.target_dyn_into::&lt;web_sys::HtmlInputElement&gt;().unwrap();
                                user_state.set((input.value(), user_state.<span class="hljs-number">1</span>.clone(), user_state.<span class="hljs-number">2</span>));
                            }
                        })}
                        class=<span class="hljs-string">"border rounded px-4 py-2 mr-2"</span>
                    /&gt;
                    &lt;input
                        placeholder=<span class="hljs-string">"Email"</span>
                        value={user_state.<span class="hljs-number">1</span>.clone()}
                        oninput={Callback::from({
                            <span class="hljs-keyword">let</span> user_state = user_state.clone();
                            <span class="hljs-keyword">move</span> |e: InputEvent| {
                                <span class="hljs-keyword">let</span> input = e.target_dyn_into::&lt;web_sys::HtmlInputElement&gt;().unwrap();
                                user_state.set((user_state.<span class="hljs-number">0</span>.clone(), input.value(), user_state.<span class="hljs-number">2</span>));
                            }
                        })}
                        class=<span class="hljs-string">"border rounded px-4 py-2 mr-2"</span>
                    /&gt;

                    &lt;button
                        onclick={<span class="hljs-keyword">if</span> user_state.<span class="hljs-number">2</span>.is_some() { update_user.clone() } <span class="hljs-keyword">else</span> { create_user.clone() }}
                        class=<span class="hljs-string">"bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"</span>
                    &gt;
                        { <span class="hljs-keyword">if</span> user_state.<span class="hljs-number">2</span>.is_some() { <span class="hljs-string">"Update User"</span> } <span class="hljs-keyword">else</span> { <span class="hljs-string">"Create User"</span> } }

                    &lt;/button&gt;
                        <span class="hljs-keyword">if</span> !message.is_empty() {
                        &lt;p class=<span class="hljs-string">"text-green-500 mt-2"</span>&gt;{ &amp;*message }&lt;/p&gt;
                    }
                &lt;/div&gt;

                &lt;button
                    onclick={get_users.reform(|_| ())}  
                    class=<span class="hljs-string">"bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded mb-4"</span>
                &gt;
                    { <span class="hljs-string">"Fetch User List"</span> }
                &lt;/button&gt;

                &lt;h2 class=<span class="hljs-string">"text-2xl font-bold text-gray-700 mb-2"</span>&gt;{ <span class="hljs-string">"User List"</span> }&lt;/h2&gt;

                &lt;ul class=<span class="hljs-string">"list-disc pl-5"</span>&gt;
                    { <span class="hljs-keyword">for</span> (*users).iter().map(|user| {
                        <span class="hljs-keyword">let</span> user_id = user.id;
                        html! {
                            &lt;li class=<span class="hljs-string">"mb-2"</span>&gt;
                                &lt;span class=<span class="hljs-string">"font-semibold"</span>&gt;{ <span class="hljs-built_in">format!</span>(<span class="hljs-string">"ID: {}, Name: {}, Email: {}"</span>, user.id, user.name, user.email) }&lt;/span&gt;
                                &lt;button
                                    onclick={delete_user.clone().reform(<span class="hljs-keyword">move</span> |_| user_id)}
                                    class=<span class="hljs-string">"ml-4 bg-red-500 hover:bg-red-700 text-white font-bold py-1 px-2 rounded"</span>
                                &gt;
                                    { <span class="hljs-string">"Delete"</span> }
                                &lt;/button&gt;
                                &lt;button
                                    onclick={edit_user.clone().reform(<span class="hljs-keyword">move</span> |_| user_id)}
                                    class=<span class="hljs-string">"ml-4 bg-yellow-500 hover:bg-yellow-700 text-white font-bold py-1 px-2 rounded"</span>
                                &gt;
                                    { <span class="hljs-string">"Edit"</span> }
                                &lt;/button&gt;
                            &lt;/li&gt;
                        }
                    })}

                &lt;/ul&gt;


        &lt;/div&gt;
    }
}

<span class="hljs-meta">#[derive(Serialize, Deserialize, Clone, Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">User</span></span> {
    id: <span class="hljs-built_in">i32</span>,
    name: <span class="hljs-built_in">String</span>,
    email: <span class="hljs-built_in">String</span>,
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    yew::Renderer::&lt;App&gt;::new().render();
}
</code></pre>
<h2 id="heading-building-the-frontend">Building the Frontend</h2>
<p>It's now time to run the frontend.</p>
<p>You can type:</p>
<pre><code>cargo build --target wasm32-unknown-unknown
</code></pre><p>And then you can run the frontend by running:</p>
<pre><code class="lang-bash">trunk serve
</code></pre>
<p>You can now visit <code>http://127.0.0.1:8080</code> and click the <code>Fetch User List</code> button to fetch the users from the backend: </p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b980sgazvkr9jhw1g89p.png" alt="Build a rust fullstack web application" /></a></p>
<p>As you can see, we fetch users from the backend and display them in the front end. The front end also allows you to create, update, and delete users.</p>
<p>For example, we can create a user with name <code>yew</code> and email <code>yes@mail.com</code>:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yfl4w7mlgq1huu5xa0ii.png" alt="Build a rust fullstack web application" /></a></p>
<p>The user should be displayed correctly on the frontend, with the message <code>User created successfully</code>:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jmuwyvtcu5onh3dyv40p.png" alt="Build a rust fullstack web application" /></a></p>
<p>To check the consistency of data, we can use Postman, making a <code>GET</code> request to <code>http://127.0.0.1:8000/api/users</code>:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8jzza68jcbzm1kbsx3qb.png" alt="Build a rust fullstack web application" /></a></p>
<p>We can also update a user, for example, the one with ID 3, by changing the name to <code>subscribe</code> and the email to <code>subscribe@mail.com</code>. Notice that when we hit the <code>Edit</code> button, the form is populated with the user data, and the button label is changed to <code>Update User</code>:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2cbg9apnoqdunas0av22.png" alt="Build a rust fullstack web application" /></a></p>
<p>After hitting the <code>Update User</code> button, we should see the message <code>User updated successfully</code>:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9e6zg6th7a9kwd3348rt.png" alt="Build a rust fullstack web application" /></a></p>
<p>The last test is to delete a user, for example, the one with ID 3. After hitting the <code>Delete</code> button, we should see the message <code>User deleted successfully</code>:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q3z2md59qmjnh88kpomu.png" alt="Build a rust fullstack web application" /></a></p>
<p>After hitting the <code>Delete</code> button, we should see the message <code>User deleted successfully</code>:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fs48v7ulz8b3dqc8bcmd.png" alt="Build a rust fullstack web application" /></a></p>
<p><strong>Note:</strong> You should be able to see all the HTTP requests in the backend logs.</p>
<p>Let's create the last user, and let's call it <code>last</code> and let's use as email <code>last@mail.com</code></p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9htsv8zhy9stpapax0tq.png" alt="Build a rust fullstack web application" /></a></p>
<p>If we use Postman and make a <code>GET</code> request to <code>http://127.0.0.1:8000/api/users</code>, we should see the following output:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gc1sjnta8487ju7yuzop.png" alt="Build a rust fullstack web application" /></a></p>
<p>We can also see the data by opening a new tab and visiting <code>http://127.0.0.1:8000/api/users</code>:</p>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ob1sb41al9njmqfiq1x1.png" alt="Build a rust fullstack web application" /></a></p>
<p>The last test is to check it directly in the Postgres container. You can step into the container by running <code>docker exec -it db psql -U postgres</code> and then run:</p>
<pre><code class="lang-bash">\dt
select * from users;
</code></pre>
<p><a target="_blank" href="https://youtu.be/FYVbt6YFMsM"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xq8aa3by5wdxabs1gypz.png" alt="Build a rust fullstack web application" /></a></p>
<p>Well done!</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, we built a full-stack web application using Rust. We built a backend using Rocket and Postgres and a frontend using Yew, Tailwind CSS, and Trunk. We created, read, update, and deleted users from the database using the front end. We also tested the APIs using Postman and checked</p>
<iframe width="905" height="510" src="https://www.youtube.com/embed/D_76TcfzDTU "></iframe>



<p>All the code is available on <a target="_blank" href="https://youtu.be/FYVbt6YFMsM">GitHub</a> (link in video description)</p>
<p>You can find me here: https://francescociulla.com</p>
]]></content:encoded></item><item><title><![CDATA[Tutorials are great! But something is missing...]]></title><description><![CDATA[Tutorials are great. 
They provide insights and help us learn new concepts. 
But without practical application, you’ll likely forget what you’ve learned the day after. That’s why solving exercises is so important in programming. It forces your brain ...]]></description><link>https://blog.francescociulla.com/tutorials-are-great-but-something-is-missing</link><guid isPermaLink="true">https://blog.francescociulla.com/tutorials-are-great-but-something-is-missing</guid><category><![CDATA[Rust]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Thu, 08 Aug 2024 20:58:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723150624481/ab967e29-0e0f-43ca-aa4a-3ed0b9e4ba00.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Tutorials are great. </p>
<p>They provide insights and help us learn new concepts. </p>
<p>But without practical application, you’ll likely forget what you’ve learned the day after. That’s why solving exercises is so important in programming. It forces your brain to engage, solve the problem with your hands, and truly grasp the concepts.</p>
<p>In many tutorials, including mine, the student’s approach is often PASSIVE: You watch the tutorial, read the article, clone the project, run it, it works, and you think you are making progress. And yes, you do make some progress, but it’s the same progress you make by watching someone else play poker. You understand the rules but miss out on what it means to play and learn the tactics to win.</p>
<p>That's why I created <a target="_blank" href="https://francescociulla.gumroad.com/l/rustworkbook/RUSTWORKBOOK10">the Rust Workbook</a>, a collection of exercises designed to help you learn Rust by doing. These exercises are carefully crafted to guide you through solving problems, building confidence, and reinforcing your understanding of Rust's core concepts.</p>
<p>In this article I want to give you a sneak peek into the Rust Workbook, show you how the exercises are structured, and provide an example to illustrate how they work. </p>
<p>Let’s dive in!</p>
<p>To truly benefit from this exercise, try to solve it independently before peeking at the solution (give yourself at least 30 minutes). That’s when the magic happens in your brain, and that’s when real learning occurs.</p>
<p>A Simple Exercise Example: Understanding Ownership in Rust
Let's examine an exercise focused on understanding Rust's ownership system to illustrate how the exercises are structured and how they guide you through the learning process.</p>
<h2 id="heading-exercise-22-ownership">Exercise 2.2: Ownership</h2>
<h3 id="heading-introduction">Introduction</h3>
<p>In Rust, every value has an owner, the variable that holds the value. When you move a value from one variable to another, the original variable can no longer be used. You can also borrow a value using the &amp; operator, which allows you to access the value without transferring ownership.</p>
<h3 id="heading-task">Task</h3>
<p>Declare a variable, move its value to another variable, and observe what happens when using the original variable. Then, use the &amp; operator to borrow the value instead of moving it and see how this affects the original variable.</p>
<h3 id="heading-instructions">Instructions</h3>
<ol>
<li>Open your terminal, run cargo new ownership, then cd ownership.</li>
<li>Open src/main.rs in your IDE and replace its content with the code below.</li>
</ol>
<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">// Declare a variable with a string value</span>
    <span class="hljs-keyword">let</span> s1 = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);

    <span class="hljs-comment">// Move the value to a new variable (let s2 = s1)</span>
    <span class="hljs-comment">// Print both variables to see what happens</span>

    <span class="hljs-comment">// Borrow the value (let s2 = &amp;s1)</span>
    <span class="hljs-comment">// Print both the original and the borrowed variable</span>
}
</code></pre>
<ol start="3">
<li>Declare a variable with a string value using the let keyword.</li>
<li>Move the value from this variable to a new variable using the = operator (let s2 = s1;).</li>
<li>Try to print the original and the new variable to see what happens (you should encounter an error!).</li>
<li>Instead, use the &amp; operator to borrow the value from the original variable and assign it to a new variable (e.g., let s2 = &amp;s1;).</li>
<li>Print both the original and the borrowed variable to see the difference.</li>
<li>Save the file and run cargo run in the terminal to see the result.</li>
</ol>
<p>Good luck. If you need help, you can check <a target="_blank" href="https://www.youtube.com/watch?v=9VBLOwmNE1g">this video</a></p>
<p>Once you have tried to solve the exercise, you can check the solution below.</p>
<hr />
<h2 id="heading-solution-to-exercise-22-ownership">Solution to Exercise 2.2: Ownership</h2>
<p>Solution Overview</p>
<p>In this exercise, you were asked to explore Rust's ownership system by declaring a variable, moving its value to another variable, and observing what happens when you try to use the original variable. You also used the &amp; operator to borrow the value instead of moving it, which allowed you to see how borrowing works in Rust.</p>
<h3 id="heading-final-code">Final Code</h3>
<p>Here’s the code that achieves the task:</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">// Declare a variable with a string value</span>
    <span class="hljs-keyword">let</span> s1 = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);

    <span class="hljs-comment">// Move the value to a new variable (s1 is no longer valid after this point)</span>
    <span class="hljs-keyword">let</span> s2 = s1;

    <span class="hljs-comment">// Uncommenting the following line would cause a compile-time error because s1 has been moved</span>
    <span class="hljs-comment">// println!("s1: {}", s1); // This would cause an error</span>

    <span class="hljs-comment">// Print the new variable</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"s2: {}"</span>, s2);

    <span class="hljs-comment">// Borrow the value from s2 using a reference</span>
    <span class="hljs-keyword">let</span> s3 = &amp;s2;

    <span class="hljs-comment">// Print both the original and the borrowed variable</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"s2: {}"</span>, s2);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"s3: {}"</span>, s3);
}
</code></pre>
<h3 id="heading-program-output">Program Output</h3>
<p>When you run the program using cargo run, you will see this output in your terminal:</p>
<pre><code class="lang-bash">s2: hello
s2: hello
s3: hello
</code></pre>
<p>Explanation</p>
<ul>
<li><p><strong>Ownership Transfer (Move):</strong> The line let s2 = s1; moves the String ownership from s1 to s2. After this move, s1 is no longer valid, and any attempt to use s1 would result in a compile-time error.</p>
</li>
<li><p><strong>Borrowing with References:</strong> The line let s3 = &amp;s2; creates a reference to s2, meaning s3 borrows the value of s2 without taking ownership. This allows both s2 and s3 to be used without transferring ownership.</p>
</li>
<li><p><strong>Error Prevention:</strong> Rust's ownership system ensures memory safety by preventing multiple data ownership. Once a value is moved, the original variable can no longer be used, which prevents dangling references or double-free errors.</p>
</li>
</ul>
<p>This exercise demonstrates how Rust's ownership model works, including how values can be moved between variables and how references can be used to borrow values without taking ownership. </p>
<p>It’s not about making things difficult—it’s about guiding you through the process, step by step, to help you understand how Rust manages memory safely.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>This example highlights how the exercises in this workbook are designed. They may not be overly challenging, but they are structured to guide you through the learning process, helping you build a solid understanding of Rust's core concepts. </p>
<p>The book encourages you to think critically about your code and understand the underlying principles by taking a step-by-step approach.</p>
<p>Remember, the real value of this workbook lies in solving the exercises. Take your time, work through them methodically, and you’ll find that even simple exercises can lead to deep insights into how Rust works.</p>
<p>If you like this style and you want more exercises like the one above, check out the <a target="_blank" href="https://francescociulla.gumroad.com/l/rustworkbook/RUSTWORKBOOK10">full Rust Workbook</a>.
<a target="_blank" href="https://www.rust-workbook.dev/"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aaqxzk9le85wkimwv067.png" alt="Rust workbook" />
</a></p>
]]></content:encoded></item><item><title><![CDATA[3 Common Mistakes Beginners Make When Learning Rust]]></title><description><![CDATA[In 2024, the Stack Overflow Developer Survey voted Rust the most admired language. Rust's unique combination of performance, safety, and ergonomics has made it a popular choice for systems programming, web development, blockchain, and more.
However, ...]]></description><link>https://blog.francescociulla.com/3-common-mistakes-beginners-make-when-learning-rust</link><guid isPermaLink="true">https://blog.francescociulla.com/3-common-mistakes-beginners-make-when-learning-rust</guid><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Rust]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Sun, 04 Aug 2024 09:57:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722765395880/eb05f340-aa88-4cc2-bf86-9ca5a802a735.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In 2024, the Stack Overflow Developer Survey voted Rust the most admired language. Rust's unique combination of performance, safety, and ergonomics has made it a popular choice for systems programming, web development, blockchain, and more.</p>
<p>However, as with any powerful tool, getting the most out of Rust requires a solid understanding of its fundamentals. </p>
<p>In this article, I want to share three common mistakes beginners often make when learning Rust and practical solutions to help you avoid them. </p>
<p>All the code is available and open source here: https://github.com/FrancescoXX/three-rust-mistakes</p>
<p>Let's get started!</p>
<hr />
<h2 id="heading-1-confusion-around-the-let-keyword">1. Confusion Around the let Keyword</h2>
<p>If you're from a JavaScript background, you might find Rust's <code>let</code> keyword familiar yet surprisingly different. </p>
<h3 id="heading-example">Example:</h3>
<p>In JavaScript, you can reassign a variable declared with <code>let</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> x = <span class="hljs-number">10</span>;
x = <span class="hljs-number">20</span>;  <span class="hljs-comment">// Reassignment is allowed</span>

<span class="hljs-built_in">console</span>.log(x);  <span class="hljs-comment">// Outputs: 20</span>
</code></pre>
<p>..But if we try to do the same in Rust, we'll encounter a compile-time error:</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> x = <span class="hljs-number">10</span>;
    x = <span class="hljs-number">20</span>;  <span class="hljs-comment">// This will cause a compile-time error in Rust</span>

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, x);
}
</code></pre>
<p>Why? In Rust, variables are immutable by default, meaning you can't reassign a value unless you explicitly declare the variable as mutable:</p>
<p>While <code>let</code> in both languages is used to declare variables, Rust’s strict handling of mutability and scope can be a source of confusion.</p>
<h3 id="heading-solution">Solution:</h3>
<p>To allow reassignment, you must declare the variable as mutable using the <code>mut</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-keyword">let</span> <span class="hljs-keyword">mut</span> x = <span class="hljs-number">10</span>;  <span class="hljs-comment">// Declare x as mutable</span>
    x = <span class="hljs-number">20</span>;  <span class="hljs-comment">// Now reassignment is allowed</span>

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, x);  <span class="hljs-comment">// Outputs: 20</span>
}
</code></pre>
<p>If you want to learn more about variables in Rust, check out <a target="_blank" href="https://www.youtube.com/watch?v=6Ag0MZUlvBE">this YouTube video</a> </p>
<hr />
<h2 id="heading-2-misunderstanding-ownership-and-borrowing">2. Misunderstanding Ownership and Borrowing</h2>
<p>One of Rust's most distinctive and powerful features is its ownership model. </p>
<p>While this model ensures memory safety without a garbage collector, it can be tricky for beginners to grasp fully. </p>
<p>Misunderstanding ownership and borrowing often leads to common errors like "value borrowed after move" or "cannot borrow as mutable."</p>
<h3 id="heading-example-1">Example:</h3>
<p>Consider the following 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> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Hello, Rust!"</span>);
    <span class="hljs-keyword">let</span> s2 = s;  <span class="hljs-comment">// Ownership moves to s2, s is no longer valid</span>

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, s);  <span class="hljs-comment">// This will cause a compile-time error</span>
}
</code></pre>
<p>In this example, when we assign s to s2, the ownership of the data is transferred to s2. As a result, s is no longer valid, and attempting to use it will cause a compile-time error!</p>
<h3 id="heading-solution-1">Solution:</h3>
<p>To avoid this mistake, you can <code>borrow</code> the value instead of transferring ownership. </p>
<p>Borrowing allows you to reference the original value without taking ownership, ensuring that the original variable remains valid:</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> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Hello, Rust!"</span>);
    <span class="hljs-keyword">let</span> s2 = &amp;s;  <span class="hljs-comment">// Borrowing s, s is still valid</span>

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, s);   <span class="hljs-comment">// This will work</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, s2);  <span class="hljs-comment">// This will also work</span>
}
</code></pre>
<p>By using a <code>&amp;s</code> reference , we can access the value without transferring ownership, allowing both s and s2 to coexist without errors.</p>
<p>Understanding ownership and borrowing is crucial to mastering Rust. </p>
<p>If you want a deeper dive into these concepts, check out <a target="_blank" href="https://youtu.be/9VBLOwmNE1g?si=GAyJVNq5ZQVz9Fl8">this YouTube video on Rust's ownership model</a>. </p>
<hr />
<h2 id="heading-3-ignoring-error-handling">3. Ignoring Error Handling</h2>
<p>While it's tempting to ignore error checks and use <code>unwrap</code> to quickly access values, doing so can lead to unexpected panics and runtime errors if something goes wrong. </p>
<p>Rust's <code>Result</code> type provides a powerful mechanism for handling errors safely and concisely, ensuring your program can gracefully deal with unexpected situations.</p>
<h3 id="heading-example-2">Example:</h3>
<p>Consider the following code snippet that reads a file and prints its contents:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::fs::File;
<span class="hljs-keyword">use</span> std::io::Read;

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> file = File::open(<span class="hljs-string">"example.txt"</span>);
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> contents = <span class="hljs-built_in">String</span>::new();
    file.unwrap().read_to_string(&amp;<span class="hljs-keyword">mut</span> contents).unwrap();  <span class="hljs-comment">// This can panic if the file doesn't exist</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, contents);
}
</code></pre>
<p>In this example, the <code>open</code> method returns a <code>Result</code> type that represents the operation's success or failure. </p>
<p>Using <code>unwrap</code> on the <code>Result</code> can cause the program to panic if the file doesn’t exist or if there's another error.</p>
<h3 id="heading-solution-2">Solution:</h3>
<p>To handle errors properly, you can use the match expression to check the Result and handle both success and failure cases:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::fs::File;
<span class="hljs-keyword">use</span> std::io::{<span class="hljs-keyword">self</span>, Read};

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> file = File::open(<span class="hljs-string">"example.txt"</span>);

    <span class="hljs-keyword">match</span> file {
        <span class="hljs-literal">Ok</span>(<span class="hljs-keyword">mut</span> f) =&gt; {
            <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> contents = <span class="hljs-built_in">String</span>::new();
            <span class="hljs-keyword">match</span> f.read_to_string(&amp;<span class="hljs-keyword">mut</span> contents) {
                <span class="hljs-literal">Ok</span>(_) =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, contents),
                <span class="hljs-literal">Err</span>(e) =&gt; eprintln!(<span class="hljs-string">"Error reading file: {}"</span>, e),
            }
        }
        <span class="hljs-literal">Err</span>(e) =&gt; eprintln!(<span class="hljs-string">"Error opening file: {}"</span>, e),
    }
}
</code></pre>
<p>In this solution, instead of using <code>unwrap</code>, we handle the Result explicitly with a <code>match</code> statement (here is a <a target="_blank" href="https://www.youtube.com/watch?v=sd1M_CLXl4I">video about the match statement</a>). </p>
<p>This approach ensures errors are caught and handled, preventing unexpected panics and making the code more robust.</p>
<h3 id="heading-using-the-operator">Using the ? Operator:</h3>
<p>For even more concise error handling, Rust provides the <code>?</code> operator, which can be used to propagate errors up the call stack:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::fs::File;
<span class="hljs-keyword">use</span> std::io::{<span class="hljs-keyword">self</span>, Read};

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">read_file</span></span>() -&gt; io::<span class="hljs-built_in">Result</span>&lt;<span class="hljs-built_in">String</span>&gt; {
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> file = File::open(<span class="hljs-string">"example.txt"</span>)?;
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> contents = <span class="hljs-built_in">String</span>::new();
    file.read_to_string(&amp;<span class="hljs-keyword">mut</span> contents)?;
    <span class="hljs-literal">Ok</span>(contents)
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">match</span> read_file() {
        <span class="hljs-literal">Ok</span>(contents) =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, contents),
        <span class="hljs-literal">Err</span>(e) =&gt; eprintln!(<span class="hljs-string">"Error: {}"</span>, e),
    }
}
</code></pre>
<p>Here, the <code>?</code> operator handles errors in a way that keeps the code clean and readable while still ensuring that errors are correctly managed.</p>
<p>If you want an introduction to Error Handling in Rust, check out <a target="_blank" href="https://youtu.be/6AkRRzcAUKk?si=53xxjzGfhYrHRMfP">this YouTube video</a>.</p>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Rust is an excellent language, but it takes time to get used to its quirks and unique features, like any new tool.</p>
<p>Remember, everyone makes mistakes, and it's normal while learning a new programming language, especially one as powerful and unique as Rust.</p>
<p>If you want to learn more about Rust, I have a <a target="_blank" href="https://www.youtube.com/watch?v=R33h77nrMqc&amp;list=PLPoSdR46FgI412aItyJhj2bF66cudB6Qs&amp;index=1">Rust YouTube playlist</a> where I post a complete course for beginner Rust developers.</p>
<p>All the code is available and open source here: https://github.com/FrancescoXX/three-rust-mistakes</p>
<p>Have fun writing Rust code!</p>
<p>Francesco</p>
]]></content:encoded></item><item><title><![CDATA[Getting familiar with Rust's Syntax]]></title><description><![CDATA[So, you've decided to learn Rust.
Good choice! Rust is an awesome language that combines the power of systems programming with modern language features, and it can be used for Web Development and blockchain. 
However, when learning Rust, one of the b...]]></description><link>https://blog.francescociulla.com/getting-familiar-with-rusts-syntax</link><guid isPermaLink="true">https://blog.francescociulla.com/getting-familiar-with-rusts-syntax</guid><category><![CDATA[Rust]]></category><category><![CDATA[rust lang]]></category><category><![CDATA[Rust programming]]></category><category><![CDATA[rustseries]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Sat, 03 Aug 2024 05:41:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722663562408/6a7864d8-f9ce-4d19-b2d4-eda3d895746f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>So, you've decided to learn Rust.</p>
<p>Good choice! Rust is an awesome language that combines the power of systems programming with modern language features, and it can be used for Web Development and blockchain. </p>
<p>However, when learning Rust, one of the blockers is getting familiar with its Syntax.</p>
<p>In this article, I'll do my best to provide examples that will make you feel comfortable with them.</p>
<h2 id="heading-getting-started-variables-and-types">Getting Started: Variables and Types</h2>
<p>Let's start with the basics: variables. </p>
<p>By default, Rust variables are immutable. This might sound weird if you're used to languages like Python or JavaScript, which allow variables to change. </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> x = <span class="hljs-number">5</span>; <span class="hljs-comment">// x is immutable by default</span>
    <span class="hljs-comment">// x = 6; // Uncommenting this will throw a compiler error</span>

    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> y = <span class="hljs-number">5</span>; <span class="hljs-comment">// y is mutable</span>
    y = <span class="hljs-number">6</span>; <span class="hljs-comment">// No problem here</span>
}
</code></pre>
<p>Notice the <code>let</code> keyword? That's how you declare variables in Rust. If you want to change a variable, make it mutable with the mut keyword. </p>
<h2 id="heading-type-annotations">Type Annotations</h2>
<p>Rust has great type inference: the compiler usually knows your variables' type. </p>
<p>But sometimes, you'll need to specify the type yourself:</p>
<pre><code class="lang-rust"><span class="hljs-comment">// Here, we're explicitly saying that z is a 32-bit integer</span>
<span class="hljs-keyword">let</span> z: <span class="hljs-built_in">i32</span> = <span class="hljs-number">10</span>;
</code></pre>
<p>Rust's type system is one of its great advantages, so it’s worth getting comfortable with it early on.</p>
<h2 id="heading-functions">Functions</h2>
<p>Functions in Rust look pretty familiar if you've worked with other languages. But there are some syntax quirks to watch out for.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">add</span></span>(a: <span class="hljs-built_in">i32</span>, b: <span class="hljs-built_in">i32</span>) -&gt; <span class="hljs-built_in">i32</span> {
    a + b <span class="hljs-comment">// No semicolon means this is the return value</span>
}
</code></pre>
<p>Notice that we’re using -&gt; to define the function's return type. Also, there's no return keyword here; Rust returns the last expression by default if you omit the semicolon. </p>
<p>It’s nice once you get used to it.</p>
<h2 id="heading-ownership-and-borrowing">Ownership and Borrowing</h2>
<p>Alright, here’s where things get interesting. Rust’s ownership model makes it stand out but can be tricky at first. </p>
<p>Let’s see another example</p>
<h3 id="heading-ownership">Ownership</h3>
<p>In Rust, each value has a variable, which is its owner. </p>
<p>When the owner goes out of scope, the value is dropped. This is how Rust avoids memory leaks.</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> s1 = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);
    <span class="hljs-keyword">let</span> s2 = s1; <span class="hljs-comment">// Ownership of the String is moved to s2, s1 is now invalid</span>

    <span class="hljs-comment">// println!("{}", s1); // This would cause a compile-time error</span>
}
</code></pre>
<p>Here, s1 no longer owns the String after it’s moved to s2. </p>
<p>If you try to use s1 after that, Rust won’t let you. It’s like Rust says: "Hey, that’s not yours anymore."</p>
<h3 id="heading-borrowing">Borrowing</h3>
<p>But what if you want to use a value without taking ownership of it? </p>
<p>That’s where borrowing comes in. You can borrow a value by using references:</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> s1 = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);
    <span class="hljs-keyword">let</span> len = calculate_length(&amp;s1); <span class="hljs-comment">// We're borrowing s1 here</span>

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"The length of '{}' is {}."</span>, s1, len);
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">calculate_length</span></span>(s: &amp;<span class="hljs-built_in">String</span>) -&gt; <span class="hljs-built_in">usize</span> {
    s.len()
}
</code></pre>
<p>In this example, &amp;s1 is a <code>reference</code> to s1. The calculate_length function temporarily borrows s1 without taking ownership. After the function is done, s1 is still valid. That's pretty cool.</p>
<h2 id="heading-lifetimes">Lifetimes</h2>
<p>Lifetimes are how Rust keeps track of how long references are valid. </p>
<p>They can be confusing initially, but they’re crucial for safe memory management.</p>
<p>Let's see a very basic example, to get familiar with it.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">longest</span></span>&lt;<span class="hljs-symbol">'a</span>&gt;(x: &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">str</span>, y: &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">str</span>) -&gt; &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">str</span> {
    <span class="hljs-keyword">if</span> x.len() &gt; y.len() {
        x
    } <span class="hljs-keyword">else</span> {
        y
    }
}
</code></pre>
<p>Here, 'a is a lifetime parameter. It means the references x and y must live at least as long as the return value. This ensures that we don’t return a reference to something that’s already been dropped.</p>
<h2 id="heading-pattern-matching">Pattern Matching</h2>
<p>Rust's match statement is like a switch on steroids. It’s one of my favorite parts of the language because it’s so powerful and expressive.</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> number = <span class="hljs-number">7</span>;

    <span class="hljs-keyword">match</span> number {
        <span class="hljs-number">1</span> =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"One!"</span>),
        <span class="hljs-number">2</span> =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Two!"</span>),
        <span class="hljs-number">3</span> | <span class="hljs-number">4</span> | <span class="hljs-number">5</span> =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Three, Four, or Five!"</span>),
        <span class="hljs-number">6</span>..=<span class="hljs-number">10</span> =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Between Six and Ten!"</span>),
        _ =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Anything else!"</span>),
    }
}
</code></pre>
<p>The match statement checks a value against multiple patterns and runs the code for the first matching pattern. The _ is a catch-all pattern, which is useful when you want to handle anything you haven’t explicitly matched.</p>
<h2 id="heading-destructuring-with-pattern-matching">Destructuring with Pattern Matching</h2>
<p>You can also use <code>match</code> to destructure complex data types like tuples or enums.</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> pair = (<span class="hljs-number">2</span>, <span class="hljs-number">5</span>);

    <span class="hljs-keyword">match</span> pair {
        (<span class="hljs-number">0</span>, y) =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"First is zero and y is {}"</span>, y),
        (x, <span class="hljs-number">0</span>) =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"x is {} and second is zero"</span>, x),
        _ =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"No zeroes here!"</span>),
    }
}
</code></pre>
<p>This is just scratching the surface. </p>
<p>Match can do much more, but this should give you a solid foundation.</p>
<h2 id="heading-error-handling">Error Handling</h2>
<p>Rust doesn’t have exceptions. Instead, it uses the Result and Option types for error handling. It might feel a bit verbose initially, but it’s much safer than unchecked exceptions.</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> result = divide(<span class="hljs-number">10</span>, <span class="hljs-number">2</span>);
    <span class="hljs-keyword">match</span> result {
        <span class="hljs-literal">Ok</span>(v) =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Result is {}"</span>, v),
        <span class="hljs-literal">Err</span>(e) =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Error: {}"</span>, e),
    }
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">divide</span></span>(a: <span class="hljs-built_in">i32</span>, b: <span class="hljs-built_in">i32</span>) -&gt; <span class="hljs-built_in">Result</span>&lt;<span class="hljs-built_in">i32</span>, <span class="hljs-built_in">String</span>&gt; {
    <span class="hljs-keyword">if</span> b == <span class="hljs-number">0</span> {
        <span class="hljs-literal">Err</span>(<span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Division by zero"</span>))
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-literal">Ok</span>(a / b)
    }
}
</code></pre>
<p>Here, <code>Result</code> is a type that can be either Ok (success) or Err (error). This forces you to handle success and failure cases, which is great for writing robust code.</p>
<h2 id="heading-the-operator">The <code>?</code> Operator</h2>
<p>To make error handling a bit more ergonomic, Rust provides the <code>?</code> Operator. It’s a shorthand for propagating errors.</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;(), <span class="hljs-built_in">String</span>&gt; {
    <span class="hljs-keyword">let</span> result = divide(<span class="hljs-number">10</span>, <span class="hljs-number">0</span>)?; <span class="hljs-comment">// If divide returns Err, it returns from the function immediately</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Result is {}"</span>, result);
    <span class="hljs-literal">Ok</span>(())
}
</code></pre>
<p>This is Rust's saying, “If there’s an error, just return it.”</p>
<h2 id="heading-advanced-syntax-traits-generics-and-more">Advanced Syntax: Traits, Generics, and More</h2>
<p>Now that we've got the basics down, let's dive into more advanced topics.</p>
<h3 id="heading-traits-interfaces-kinda">Traits: Interfaces (Kinda)</h3>
<p>Traits are kind of like interfaces in other languages. They define shared behavior that different types can implement.</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Summary</span></span> {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">summarize</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">String</span>;
}

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Article</span></span> {
    title: <span class="hljs-built_in">String</span>,
    content: <span class="hljs-built_in">String</span>,
}

<span class="hljs-keyword">impl</span> Summary <span class="hljs-keyword">for</span> Article {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">summarize</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">String</span> {
        <span class="hljs-built_in">format!</span>(<span class="hljs-string">"{}: {}"</span>, <span class="hljs-keyword">self</span>.title, <span class="hljs-keyword">self</span>.content)
    }
}
</code></pre>
<p>Here, we define and implement a Summary trait for the Article struct. Now, any Article can be summarized. Traits are super powerful for writing generic and reusable code.</p>
<h3 id="heading-generics-writing-flexible-code">Generics: Writing Flexible Code</h3>
<p>Generics let you write functions and types that work with any data type.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">largest</span></span>&lt;T: <span class="hljs-built_in">PartialOrd</span>&gt;(list: &amp;[T]) -&gt; &amp;T {
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> largest = &amp;list[<span class="hljs-number">0</span>];
    <span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> list {
        <span class="hljs-keyword">if</span> item &gt; largest {
            largest = item;
        }
    }
    largest
}
</code></pre>
<p>This function works with any type T that can be compared. The PartialOrd part is trait-bound, meaning that T must implement the PartialOrd trait, which allows for ordering comparisons.</p>
<h2 id="heading-practical-tips-writing-idiomatic-rust">Practical Tips: Writing Idiomatic Rust</h2>
<ul>
<li><p>Use rustfmt: Rust has a built-in formatter that keeps your code looking sharp. Just run cargo fmt in your project directory.</p>
</li>
<li><p>Use Rust Analyzer: This powerful IDE extension provides code completion, refactoring, and more. It’s like having an assistant that knows Rust inside and out.</p>
</li>
<li><p>Clippy: This is a linter for Rust that catches common mistakes and suggests improvements. Run cargo clippy to see what it finds.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This quick article is to get a bit more familiar with Rust.</p>
<p>I have a series of free videos about these specific topics.</p>
<p>You can check it out here</p>
]]></content:encoded></item><item><title><![CDATA[How to Write Tests in Rust]]></title><description><![CDATA[Testing is an essential part of software development, especially when coding professionally and improving your code's quality. 
In Rust, testing is built into the language, making writing and running tests straightforward. 
This article will introduc...]]></description><link>https://blog.francescociulla.com/how-to-write-tests-in-rust</link><guid isPermaLink="true">https://blog.francescociulla.com/how-to-write-tests-in-rust</guid><category><![CDATA[Testing]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Tue, 30 Jul 2024 13:00:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722343171003/af476bae-a2df-4f8a-842b-2f98c856ca92.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Testing is an essential part of software development, especially when coding professionally and improving your code's quality. </p>
<p>In Rust, testing is built into the language, making writing and running tests straightforward. </p>
<p>This article will introduce you to the basics of testing in Rust with practical examples.</p>
<p>If you prefer a video version
<a target="_blank" href="https://youtu.be/UyJ1mEqKMvE"><img src="https://res.cloudinary.com/daily-now/image/upload/s--A-DL_waS--/f_auto/v1722342953/ugc/content_008d6952-67a9-4958-b46c-d5ff1f9816f5" alt="VARIABLES (40)" /></a></p>
<h3 id="heading-create-the-lib-project">Create the lib project</h3>
<p>In this case, we will create a library project using the following command:</p>
<pre><code class="lang-shell">cargo new adder --lib
</code></pre>
<p>Remember to use the --bin flag to create a binary project.</p>
<p>To run the tests, you can use the following command:</p>
<pre><code class="lang-shell">cargo test
</code></pre>
<p>This command will compile the code and run the tests.</p>
<p>Now let's create a simple function to test.</p>
<h3 id="heading-basic-test-function">Basic Test Function</h3>
<p>Let's start with a simple test function. In Rust, test functions are annotated with #[test].</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[cfg(test)]</span>
<span class="hljs-keyword">mod</span> tests {
    <span class="hljs-meta">#[test]</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">it_works</span></span>() {
        <span class="hljs-built_in">assert_eq!</span>(<span class="hljs-number">2</span> + <span class="hljs-number">2</span>, <span class="hljs-number">4</span>);
    }
}
</code></pre>
<p>In this example, the #[cfg(test)] attribute ensures that the test module is only compiled when running tests. The #[test] attribute marks the function as a test.</p>
<p>The assert_eq! macro checks if the two arguments are equal. If they are not, the test will fail.</p>
<p>The output of the test will look like this:</p>
<pre><code class="lang-shell">running 1 test
test tests::it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
</code></pre>
<h3 id="heading-making-a-test-that-fails">Making a Test That Fails</h3>
<p>It's often useful to see what happens when a test fails. </p>
<p>Here's an example:</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[cfg(test)]</span>
<span class="hljs-keyword">mod</span> tests {
    <span class="hljs-meta">#[test]</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">it_fails</span></span>() {
        <span class="hljs-built_in">assert_eq!</span>(<span class="hljs-number">2</span> + <span class="hljs-number">2</span>, <span class="hljs-number">5</span>);
    }
}
</code></pre>
<p>When you run this test, it will fail, and you'll see an error message like this:</p>
<pre><code>---- it_fails stdout ----
thread <span class="hljs-string">'tests::it_fails'</span> panicked at <span class="hljs-string">'assertion failed: `(left == right)`
  left: `4`,
 right: `5`'</span>, src/lib.rs:<span class="hljs-number">4</span>:<span class="hljs-number">9</span>
<span class="hljs-attr">note</span>: run <span class="hljs-keyword">with</span> <span class="hljs-string">`RUST_BACKTRACE=1`</span> environment variable to display a backtrace
</code></pre><h3 id="heading-using-the-assert-macro">Using the assert! Macro</h3>
<p>The assert! macro is used to check boolean expressions. If the expression evaluates to false, the test will fail.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[cfg(test)]</span>
<span class="hljs-keyword">mod</span> tests {
    <span class="hljs-meta">#[test]</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">check_true</span></span>() {
        <span class="hljs-built_in">assert!</span>(<span class="hljs-literal">true</span>);
    }
}
</code></pre>
<h3 id="heading-testing-equality-with-asserteq-and-assertne">Testing Equality with assert_eq! and assert_ne!</h3>
<p>The assert_eq! macro checks if two values are equal, while assert_ne! checks if they are not.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[cfg(test)]</span>
<span class="hljs-keyword">mod</span> tests {
    <span class="hljs-meta">#[test]</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">test_equality</span></span>() {
        <span class="hljs-built_in">assert_eq!</span>(<span class="hljs-number">3</span> * <span class="hljs-number">3</span>, <span class="hljs-number">9</span>);
        <span class="hljs-built_in">assert_ne!</span>(<span class="hljs-number">3</span> * <span class="hljs-number">3</span>, <span class="hljs-number">8</span>);
    }
}
</code></pre>
<h3 id="heading-adding-custom-failure-messages">Adding Custom Failure Messages</h3>
<p>You can add custom failure messages to your tests using the assert! macro.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[cfg(test)]</span>
<span class="hljs-keyword">mod</span> tests {
    <span class="hljs-meta">#[test]</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">custom_message</span></span>() {
        <span class="hljs-built_in">assert_eq!</span>(<span class="hljs-number">2</span> + <span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-string">"Math is broken!"</span>);
    }
}
</code></pre>
<p>In this example, the test will fail with the message "Math is broken!".</p>
<p>The output will look like this:</p>
<pre><code>---- custom_message stdout ----
thread <span class="hljs-string">'tests::custom_message'</span> panicked at <span class="hljs-string">'assertion failed: `(left == right)`
  left: `4`,
 right: `5`: Math is broken!'</span>, src/lib.rs:<span class="hljs-number">4</span>:<span class="hljs-number">9</span>
</code></pre><h3 id="heading-checking-for-panics-with-shouldpanic">Checking for Panics with should_panic</h3>
<p>You can test if a function panics using the should_panic attribute.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[cfg(test)]</span>
<span class="hljs-keyword">mod</span> tests {
    <span class="hljs-meta">#[test]</span>
    <span class="hljs-meta">#[should_panic]</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">it_panics</span></span>() {
        <span class="hljs-built_in">panic!</span>(<span class="hljs-string">"This test will panic"</span>);
    }
}
</code></pre>
<h3 id="heading-using-result-in-tests">Using Result in Tests</h3>
<p>Test functions can return Result&lt;(), E&gt; to use the ? operator for error handling.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[cfg(test)]</span>
<span class="hljs-keyword">mod</span> tests {
    <span class="hljs-meta">#[test]</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">test_with_result</span></span>() -&gt; <span class="hljs-built_in">Result</span>&lt;(), <span class="hljs-built_in">String</span>&gt; {
        <span class="hljs-keyword">if</span> <span class="hljs-number">2</span> + <span class="hljs-number">2</span> == <span class="hljs-number">4</span> {
            <span class="hljs-literal">Ok</span>(())
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-literal">Err</span>(<span class="hljs-string">"Math is broken"</span>.into())
        }
    }
}
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Rust makes testing easy and powerful with its built-in features. </p>
<p>By using attributes like #[test], assert!, assert_eq!, and should_panic, you can write robust tests for your code. </p>
<p>If you prefer a video version
<a target="_blank" href="https://youtu.be/UyJ1mEqKMvE"><img src="https://res.cloudinary.com/daily-now/image/upload/s--A-DL_waS--/f_auto/v1722342953/ugc/content_008d6952-67a9-4958-b46c-d5ff1f9816f5" alt="VARIABLES (40)" /></a></p>
]]></content:encoded></item><item><title><![CDATA[Announcing Rust 1.80.0]]></title><description><![CDATA[Announcing Rust 1.80.0
The Rust team just announced the release of Rust 1.80.0. 
This article aims to give you a quick recap of the main updates.
To update to this latest version, run:
$ rustup update stable

Key Updates in Rust 1.80.0
LazyCell and L...]]></description><link>https://blog.francescociulla.com/announcing-rust-1800</link><guid isPermaLink="true">https://blog.francescociulla.com/announcing-rust-1800</guid><category><![CDATA[General Programming]]></category><category><![CDATA[software development]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Rust]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Thu, 25 Jul 2024 14:21:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1721917238286/05e5dedd-a3c6-41a3-b761-354d8860e361.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-announcing-rust-1800">Announcing Rust 1.80.0</h2>
<p>The Rust team just announced the release of Rust 1.80.0. </p>
<p>This article aims to give you a quick recap of the main updates.</p>
<p>To update to this latest version, run:</p>
<pre><code class="lang-sh">$ rustup update stable
</code></pre>
<h2 id="heading-key-updates-in-rust-1800">Key Updates in Rust 1.80.0</h2>
<h3 id="heading-lazycell-and-lazylock">LazyCell and LazyLock</h3>
<p>These new types delay data initialization until first access. </p>
<p>LazyLock is thread-safe, suitable for static values, while LazyCell is not thread-safe but can be used in thread-local statics.</p>
<p>Example using LazyLock:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::sync::LazyLock;
<span class="hljs-keyword">use</span> std::time::Instant;

<span class="hljs-keyword">static</span> LAZY_TIME: LazyLock&lt;Instant&gt; = LazyLock::new(Instant::now);

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> start = Instant::now();
    std::thread::scope(|s| {
        s.spawn(|| {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Thread lazy time is {:?}"</span>, LAZY_TIME.duration_since(start));
        });
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Main lazy time is {:?}"</span>, LAZY_TIME.duration_since(start));
    });
}
</code></pre>
<h3 id="heading-checked-cfg-names-and-values">Checked cfg Names and Values</h3>
<p>Cargo 1.80 now includes checks for cfg names and values to catch typos and misconfigurations, improving the reliability of conditional configurations.</p>
<p>Example demonstrating cfg check:</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>);

    <span class="hljs-meta">#[cfg(feature = <span class="hljs-meta-string">"crayon"</span>)]</span>
    rayon::join(
        || <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Hello, Thing One!"</span>),
        || <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Hello, Thing Two!"</span>),
    );
}
</code></pre>
<p>Warning output:</p>
<pre><code class="lang-sh">warning: unexpected `cfg` condition value: `crayon`
 --&gt; src/main.rs:4:11
  |
4 |     <span class="hljs-comment">#[cfg(feature = "crayon")]</span>
  |           ^^^^^^^^^^--------
  |                     |
  |                     <span class="hljs-built_in">help</span>: there is an expected value with a similar name: `<span class="hljs-string">"rayon"</span>`
  |
  = note: expected values <span class="hljs-keyword">for</span> `feature` are: `rayon`
  = <span class="hljs-built_in">help</span>: consider adding `crayon` as a feature <span class="hljs-keyword">in</span> `Cargo.toml`
</code></pre>
<h3 id="heading-exclusive-ranges-in-patterns">Exclusive Ranges in Patterns</h3>
<p>Rust now supports exclusive range patterns (a..b), enhancing pattern matching and reducing the need for separate constants for inclusive endpoints.</p>
<p>Example using exclusive range patterns:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">size_prefix</span></span>(n: <span class="hljs-built_in">u32</span>) -&gt; &amp;<span class="hljs-symbol">'static</span> <span class="hljs-built_in">str</span> {
    <span class="hljs-keyword">const</span> K: <span class="hljs-built_in">u32</span> = <span class="hljs-number">10u32</span>.pow(<span class="hljs-number">3</span>);
    <span class="hljs-keyword">const</span> M: <span class="hljs-built_in">u32</span> = <span class="hljs-number">10u32</span>.pow(<span class="hljs-number">6</span>);
    <span class="hljs-keyword">const</span> G: <span class="hljs-built_in">u32</span> = <span class="hljs-number">10u32</span>.pow(<span class="hljs-number">9</span>);
    <span class="hljs-keyword">match</span> n {
        ..K =&gt; <span class="hljs-string">""</span>,
        K..M =&gt; <span class="hljs-string">"k"</span>,
        M..G =&gt; <span class="hljs-string">"M"</span>,
        G.. =&gt; <span class="hljs-string">"G"</span>,
    }
}
</code></pre>
<h3 id="heading-stabilized-apis">Stabilized APIs</h3>
<p>New stable APIs include implementations for Rc and Arc types, enhancements to Duration, Option, Seek, BinaryHeap, NonNull, and more.</p>
<h3 id="heading-read-more">Read more</h3>
<p>This is just a quick recap. For more details, check out <a target="_blank" href="https://dly.to/UOrPS3PDZrA">here</a></p>
<p>Have a great day</p>
<p><a target="_blank" href="https://francescociulla.com">Francesco</a></p>
]]></content:encoded></item><item><title><![CDATA[Exciting Announcement: My New Book on Rust Programming!]]></title><description><![CDATA[Introducing My New Book on Rust Programming!
After four and a half years of sharing free content and insights on social media, I'm excited to announce my very first paid product: a comprehensive guide to mastering Rust programming.
This book is desig...]]></description><link>https://blog.francescociulla.com/exciting-announcement-my-new-book-on-rust-programming</link><guid isPermaLink="true">https://blog.francescociulla.com/exciting-announcement-my-new-book-on-rust-programming</guid><category><![CDATA[Rust]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[100DaysOfCode]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Wed, 24 Jul 2024 15:20:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1721834389148/709087b9-84d9-4c4c-b0fd-f5504b1a3be7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Introducing My New Book on Rust Programming!</p>
<p>After four and a half years of sharing free content and insights on social media, I'm excited to announce my very first paid product: a comprehensive guide to mastering Rust programming.</p>
<p>This book is designed to take you from a complete beginner to a proficient Rust developer. </p>
<p><a target="_blank" href="https://www.rustcrab.com/"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7ogvbezc79xh90p7fkte.png" alt="Rust book cover" /></a></p>
<p>With 16 detailed chapters, it covers everything from the fundamentals to advanced topics such as pointers and multi-threading. </p>
<p>Here’s what you can expect:</p>
<p>Foundational Concepts: Start setting up your environment and writing your first Rust programs.
Core Rust Features: Understand ownership, lifetimes, and memory safety.
Advanced Techniques: Delve into pointers, concurrency, and more.
I’m committed to making Rust accessible and engaging, and this book is crafted to ensure you gain theoretical knowledge and practical skills.</p>
<p>Sign up for my newsletter for the latest updates, exclusive previews, and special offers. By subscribing, you’ll be the first to know about discounts, early access opportunities, and more.</p>
<p>Stay informed and participate in this exciting journey—subscribe to the newsletter <a target="_blank" href="https://www.rustcrab.com/">here</a>.</p>
<p>I appreciate your support!</p>
]]></content:encoded></item><item><title><![CDATA[Lifetimes in Rust explained]]></title><description><![CDATA[I want to discuss a fundamental concept you must grasp to master the Rust programming language: “Lifetimes.”
Usually, when we learn about a programming language, we reference other languages, like “it works like in JavaScript,” “it’s similar to Pytho...]]></description><link>https://blog.francescociulla.com/lifetimes-in-rust-explained</link><guid isPermaLink="true">https://blog.francescociulla.com/lifetimes-in-rust-explained</guid><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[software development]]></category><category><![CDATA[Rust]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Tue, 23 Jul 2024 13:03:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1721738226229/c99fa719-f4f9-4555-8c06-22d4f5289ede.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I want to discuss a fundamental concept you must grasp to master the Rust programming language: “Lifetimes.”</p>
<p>Usually, when we learn about a programming language, we reference other languages, like “it works like in JavaScript,” “it’s similar to Python,” and so on.</p>
<p>We can’t make this analogy in this case because “Lifetimes” are peculiar to the Rust programming language.</p>
<p>Lifetimes in Rust ensure that references are valid as long as they are used, preventing common bugs like dangling pointers and use-after-free errors.</p>
<p>This article explores lifetimes, their significance, and how to work with them through examples.</p>
<p>If you prefer a video version {% youtube w8lmMaKY3Hs %}</p>
<p>So what are lifetimes?</p>
<p>In short, Lifetimes are a form of generic parameter that describes the scope for which a reference is valid. The Rust compiler uses lifetimes to check that references do not outlive the data they point to, ensuring memory safety.</p>
<p>In Rust, every reference has a lifetime (even though you don't always see it in the code). The compiler infers lifetimes in many cases, but sometimes you need to specify them explicitly, especially in function signatures and struct definitions.</p>
<h2 id="heading-basic-example">Basic Example:</h2>
<p>Let’s see a basic example</p>
<p><a target="_blank" href="https://youtu.be/S-SkEA4QWWE"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/spfl6ui9bofizo0ap3tx.png" alt="Lifetimes in Rust" /></a></p>
<p>In this example, x is created inside an inner scope and is destroyed at the end of that scope.</p>
<p>The reference r points to x, but r is used outside the scope where x was valid. Rust's borrow checker will produce a compile-time error to prevent this situation.</p>
<h2 id="heading-explicit-lifetimes-in-function-signatures">Explicit Lifetimes in Function Signatures</h2>
<p>Sometimes, you need to write functions that accept references and return references. To ensure the references are valid, you must specify the lifetimes explicitly.</p>
<p>Consider this function that returns the longer of two string slice:</p>
<p><a target="_blank" href="https://youtu.be/S-SkEA4QWWE"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3147va7xierd5gr93ari.png" alt="Lifetimes in Rust" /></a></p>
<p>In the function longest, we declare a lifetime parameter 'a and use it to indicate that the references s1 and s2 must be valid for at least as long as the returned reference.</p>
<p>This ensures the returned reference does not outlive the data it points to.</p>
<h2 id="heading-lifetimes-in-structs">Lifetimes in Structs</h2>
<p>Lifetimes are also used in structs to ensure that references held by the struct do not outlive the struct itself.</p>
<p>Let’s see an example:</p>
<p><a target="_blank" href="https://youtu.be/S-SkEA4QWWE"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fzqnembbgteekoud4ftd.png" alt="Lifetimes in Rust" /></a></p>
<p>In this example, the ImportantExcerpt struct references a part of a string. The lifetime 'a ensures that the reference part cannot outlive the ImportantExcerpt instance, thereby preventing invalid references.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Lifetimes in Rust are a powerful feature that guarantees memory safety by ensuring references are valid for as long as they are used.</p>
<p>While the compiler often infers lifetimes, understanding and specifying them explicitly when needed is important for writing robust Rust programs.</p>
<p>With these examples and explanations, you should have a good foundation to explore more complex scenarios involving lifetimes in Rust.</p>
<p>If you prefer a video version</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/w8lmMaKY3Hs">https://youtu.be/w8lmMaKY3Hs</a></div>
]]></content:encoded></item><item><title><![CDATA[What are Traits in Rust?]]></title><description><![CDATA[Understanding Traits in Rust
Traits might sound new, but you've probably encountered the concept before. Think of them like interfaces in other languages – they define shared behavior in a way that multiple types can use. Let's break down how traits ...]]></description><link>https://blog.francescociulla.com/what-are-traits-in-rust</link><guid isPermaLink="true">https://blog.francescociulla.com/what-are-traits-in-rust</guid><category><![CDATA[Web Development]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[AI]]></category><category><![CDATA[React]]></category><category><![CDATA[Devops]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Tue, 16 Jul 2024 15:34:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1721143838178/871eb61c-03b1-424b-ba48-e4d231d252ab.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-understanding-traits-in-rust">Understanding Traits in Rust</h2>
<p>Traits might sound new, but you've probably encountered the concept before. Think of them like interfaces in other languages – they define shared behavior in a way that multiple types can use. Let's break down how traits work and why they're helpful.</p>
<p>Here's a video version if you want to check it out.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/w8lmMaKY3Hs">https://youtu.be/w8lmMaKY3Hs</a></div>
<p> </p>
<h2 id="heading-what-is-a-trait">What is a Trait?</h2>
<p>A trait in Rust defines functionality that a particular type has and can share with others. It specifies methods that can be called on a type. For example, imagine we have different types of text data: a <code>NewsArticle</code> struct for news stories and a <code>Tweet</code> struct for tweets. Both can share a typical behavior: summarizing content. We define this shared behavior using a trait.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Summary</span></span> {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">summarize</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">String</span>;
}
</code></pre>
<p>Here, the Summary trait has a <code>summarize</code> method. Any type implementing this trait must provide its own version of this method.</p>
<h2 id="heading-implementing-traits">Implementing Traits</h2>
<p>To implement a trait, you define the method specified by the trait for your type. Here's how we do it for NewsArticle and Tweet.</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">NewsArticle</span></span> {
    <span class="hljs-keyword">pub</span> headline: <span class="hljs-built_in">String</span>,
    <span class="hljs-keyword">pub</span> location: <span class="hljs-built_in">String</span>,
    <span class="hljs-keyword">pub</span> author: <span class="hljs-built_in">String</span>,
    <span class="hljs-keyword">pub</span> content: <span class="hljs-built_in">String</span>,
}

<span class="hljs-keyword">impl</span> Summary <span class="hljs-keyword">for</span> NewsArticle {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">summarize</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">String</span> {
        <span class="hljs-built_in">format!</span>(<span class="hljs-string">"{}, by {} ({})"</span>, <span class="hljs-keyword">self</span>.headline, <span class="hljs-keyword">self</span>.author, <span class="hljs-keyword">self</span>.location)
    }
}

<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Tweet</span></span> {
    <span class="hljs-keyword">pub</span> username: <span class="hljs-built_in">String</span>,
    <span class="hljs-keyword">pub</span> content: <span class="hljs-built_in">String</span>,
    <span class="hljs-keyword">pub</span> reply: <span class="hljs-built_in">bool</span>,
    <span class="hljs-keyword">pub</span> retweet: <span class="hljs-built_in">bool</span>,
}

<span class="hljs-keyword">impl</span> Summary <span class="hljs-keyword">for</span> Tweet {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">summarize</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">String</span> {
        <span class="hljs-built_in">format!</span>(<span class="hljs-string">"{}: {}"</span>, <span class="hljs-keyword">self</span>.username, <span class="hljs-keyword">self</span>.content)
    }
}
</code></pre>
<p>Now, both NewsArticle and Tweet can use the summarize method. This allows us to call summarize on instances of these types.</p>
<h2 id="heading-default-implementations">Default Implementations</h2>
<p>Traits can also have default method implementations. If we don't want to write the same method for each type, we can provide a default:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Summary</span></span> {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">summarize</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">String</span> {
        <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"(Read more...)"</span>)
    }
}
</code></pre>
<p>Types can still override this default if they need specific behavior.</p>
<h2 id="heading-using-traits-as-parameters">Using Traits as Parameters</h2>
<p>Traits can be used to define function parameters. If we want a function to accept any type that implements Summary, we can write:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">notify</span></span>(item: &amp;<span class="hljs-keyword">impl</span> Summary) {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Breaking news! {}"</span>, item.summarize());
}
</code></pre>
<p>This makes our code flexible and reusable.</p>
<h2 id="heading-returning-types-that-implement-traits">Returning Types that Implement Traits</h2>
<p>We can also specify that a function returns a type that implements a trait:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">returns_summarizable</span></span>() -&gt; <span class="hljs-keyword">impl</span> Summary {
    Tweet {
        username: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"horse_ebooks"</span>),
        content: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"of course, as you probably already know, people"</span>),
        reply: <span class="hljs-literal">false</span>,
        retweet: <span class="hljs-literal">false</span>,
    }
}
</code></pre>
<p>This allows us to return different types that conform to the Summary trait without exposing the concrete type.</p>
<h2 id="heading-conditional-implementations">Conditional Implementations</h2>
<p>Sometimes, you want methods to be available only if certain conditions are met. Rust allows conditional implementations:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span>&lt;T: Display + <span class="hljs-built_in">PartialOrd</span>&gt; Pair&lt;T&gt; {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">cmp_display</span></span>(&amp;<span class="hljs-keyword">self</span>) {
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">self</span>.x &gt;= <span class="hljs-keyword">self</span>.y {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"The largest member is x = {}"</span>, <span class="hljs-keyword">self</span>.x);
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"The largest member is y = {}"</span>, <span class="hljs-keyword">self</span>.y);
        }
    }
}
</code></pre>
<p>Here, cmp_display is only available if T implements both Display and PartialOrd.</p>
<p>Conclusion</p>
<p>Traits are a powerful feature in Rust that help define and share behavior across types. They make your code more modular, reusable, and easier to understand. By moving errors to compile time, they ensure your code is robust and efficient. Happy coding!</p>
<p>I just released a video about this topic, if you are curious, you can check it out.</p>
<p>If you prefer a video version</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/w8lmMaKY3Hs">https://youtu.be/w8lmMaKY3Hs</a></div>
]]></content:encoded></item><item><title><![CDATA[A New AI Tool for my Rust Open Source Project]]></title><description><![CDATA[Recently, I became curious about Pieces, a developer tool. Since I started a new open-source project, I thought it was a good opportunity to test something new in the AI ecosystem.
Introducing Rustcrab
Before diving into Pieces, I'd like to introduce...]]></description><link>https://blog.francescociulla.com/a-new-ai-tool-for-my-rust-open-source-project</link><guid isPermaLink="true">https://blog.francescociulla.com/a-new-ai-tool-for-my-rust-open-source-project</guid><category><![CDATA[Rust]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Developer]]></category><category><![CDATA[coding]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Fri, 12 Jul 2024 10:17:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720779407521/dac08ca6-e748-4e1b-85fd-289d3a2671ff.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Recently, I became curious about Pieces, a developer tool. Since I started a new open-source project, I thought it was a good opportunity to test something new in the AI ecosystem.</p>
<h2 id="heading-introducing-rustcrab">Introducing Rustcrab</h2>
<p>Before diving into Pieces, I'd like to introduce you to <strong>Rustcrab</strong>. Rustcrab is an open-source repository designed to be the ultimate resource hub for Rust developers. The project aims to provide meaningful information about the Rust community, resources, news, projects, dev tools, and more. You can check out Rustcrab on GitHub: <a target="_blank" href="https://github.com/FrancescoXX/rustcrab">Rustcrab</a>.</p>
<p><a target="_blank" href="https://github.com/FrancescoXX/rustcrab"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/unr3z3lim6biogpl2zvr.png" alt="Rustcrab" /></a></p>
<h2 id="heading-setting-up-pieces-suite">Setting Up Pieces Suite</h2>
<p>I installed Pieces on my Windows machine (but I'm sure other options are available).</p>
<p><a target="_blank" href="https://pieces.app/"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ih62d4i2q5yx1f8oj7wx.png" alt="Installed Pieces Suite" /></a></p>
<p>The installation process took less than a minute.</p>
<p><a target="_blank" href="https://pieces.app/"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7nbd7axqeawnfkj2rs0t.png" alt="Installation Process" /></a></p>
<p>I was prompted to allow Pieces Suite to access diagnostic information about my app, and I decided to trust them.</p>
<p><a target="_blank" href="https://pieces.app/"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2a1fvwmt55cunwsew5ft.png" alt="Diagnostic Access" /></a></p>
<p>Then, I had the choice of manual or automatic installation. I went with the automatic install.</p>
<p><a target="_blank" href="https://pieces.app/"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gxoojea673ia5xctiwl1.png" alt="Installation Choice" /></a></p>
<p>The installation process started, installing the following components:</p>
<ul>
<li><p><strong>Pieces OS</strong>: A local database server that enables Pieces to run quickly. It works both offline and inside the IDE.</p>
</li>
<li><p><strong>Pieces for Developer</strong>: Used to store code snippets, file fragments, images, and more. It requires Pieces OS to work.</p>
</li>
</ul>
<h2 id="heading-personalizing-pieces-suite">Personalizing Pieces Suite</h2>
<p>Next, I personalized my Pieces Suite setup.</p>
<p><a target="_blank" href="https://pieces.app/"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u47lpf1f12vb35b1hgw1.png" alt="Personalization Process" /></a></p>
<p>I chose Dark Mode (it was the default option, well done).</p>
<h3 id="heading-personalization-preferences">Personalization Preferences</h3>
<p>Then, I set up my preferences:</p>
<p><a target="_blank" href="https://pieces.app/"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k6858vf4w7oj6r1fq7l2.png" alt="Setup Preferences" /></a></p>
<ul>
<li><p><strong>Areas</strong>: DevOps, Frontend, Backend, and Blockchain</p>
</li>
<li><p><strong>Languages</strong>: Rust, JavaScript, TypeScript, and Python</p>
</li>
<li><p><strong>Toolchains</strong>: VSCode and Google Chrome</p>
</li>
<li><p><strong>Level</strong>: Advanced</p>
</li>
<li><p><strong>Project Type</strong>: Individual (for now)</p>
</li>
</ul>
<h3 id="heading-search-reference-amp-reuse">Search, Reference, &amp; Reuse</h3>
<p>I was prompted to set the hub for search and materials.</p>
<p><a target="_blank" href="https://pieces.app/"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2r7jerit6m9d29yc35hw.png" alt="Search Setup" /></a></p>
<p>I chose the default generative workflow and blended search as the default search engine. For sort mode, I went with the recommended option (Recent).</p>
<h3 id="heading-auto-enrichment-amp-copilot">Auto-Enrichment &amp; Copilot</h3>
<p>For control over data, I chose:</p>
<ul>
<li><p>Blended (recommended)</p>
</li>
<li><p>Mistral 7b as the default LLM runtime</p>
</li>
<li><p>No specific automatic material enrichment levels</p>
</li>
<li><p>Added the local repository for my project <a target="_blank" href="https://github.com/FrancescoXX/rustcrab">Rustcrab</a></p>
</li>
</ul>
<p><a target="_blank" href="https://pieces.app/"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m1phtf6bq60uh0b2iw2n.png" alt="Data Control" /></a></p>
<h3 id="heading-cloud-accounts-amp-integrations">Cloud Accounts &amp; Integrations</h3>
<p>I connected Pieces with my GitHub account.</p>
<p><a target="_blank" href="https://pieces.app/"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4nd5noptc8w996l9k5ab.png" alt="GitHub Integration" /></a></p>
<p>I also claimed my cloud's subdomain (<a target="_blank" href="http://francesco.pieces.cloud">francesco.pieces.cloud</a>).</p>
<p><a target="_blank" href="https://pieces.app/"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rsecchj52wfv6kdtn74d.png" alt="Claimed Subdomain" /></a></p>
<p>The onboarding process was now complete!</p>
<h2 id="heading-pieces-suite-in-action">Pieces Suite in Action</h2>
<p>Here’s how Pieces Suite looked the first time I opened it. I am definitely impressed by the UI.</p>
<p><a target="_blank" href="https://pieces.app/"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/depwbczafldxcm0gwoyh.png" alt="Pieces Suite UI" /></a></p>
<p>I then clicked on the "Add Material" button and chose "Create from scratch."</p>
<p><a target="_blank" href="https://pieces.app/"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t8j0p2rhdojyjs4x16mp.png" alt="Add Material" /></a></p>
<p>I added an existing component I used in my current project—a component that gets a repository's GitHub stars—to the "Rustcrab" project.</p>
<p><a target="_blank" href="https://pieces.app/"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vq0caxlpkmgdrocnyyhf.png" alt="Add Component" /></a></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Thanks for reading! I went through the Pieces Suite onboarding process and was impressed by the UI and features. I will definitely use it in my future projects.</p>
<p>This was just the installation and onboarding process; I might share something more in the upcoming articles.</p>
<p>If you have any comments, leave them below.</p>
<p>You can check out the Rustcrab project on GitHub: <a target="_blank" href="https://github.com/FrancescoXX/rustcrab">Rustcrab</a></p>
<p><a target="_blank" href="https://github.com/FrancescoXX/rustcrab"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/unr3z3lim6biogpl2zvr.png" alt="Rustcrab" /></a></p>
<p>You can find me here: <a target="_blank" href="https://francescociulla.com">Francesco Ciulla</a></p>
]]></content:encoded></item><item><title><![CDATA[A new project for Rust Developers??]]></title><description><![CDATA[Announcing Rustcrab: The Repository for Rust Developers That Isn't Crap
You might think I'm diving deep into Rust with what I've done so far, but that was just the beginning. Trust Francesco.
It's Time for an Announcement
I've officially started a ne...]]></description><link>https://blog.francescociulla.com/a-new-project-for-rust-developers</link><guid isPermaLink="true">https://blog.francescociulla.com/a-new-project-for-rust-developers</guid><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Rust]]></category><category><![CDATA[Developer]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Open Source]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Thu, 11 Jul 2024 12:27:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1720700748264/a2861b1e-b2bb-40ce-ab06-ddfbb8a06b41.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-announcing-rustcrab-the-repository-for-rust-developers-that-isnt-crap">Announcing Rustcrab: The Repository for Rust Developers That Isn't Crap</h2>
<p>You might think I'm diving deep into Rust with what I've done so far, but that was just the beginning. Trust Francesco.</p>
<h2 id="heading-its-time-for-an-announcement">It's Time for an Announcement</h2>
<p>I've officially started a new project called:</p>
<p><strong>"Rustcrab, the repository for Rust Developers that isn't crap"</strong></p>
<p>This project aims to create a free, open-source resource dedicated to the Rust programming language.</p>
<p>I will only share meaningful information about the Rust community, resources, news, projects, dev tools, and as much as possible. The project is 100% open-source and free.</p>
<h3 id="heading-what-ive-done-so-far">What I've Done So Far:</h3>
<ul>
<li><p>Bought the domain using NameCheap</p>
</li>
<li><p>Created a Next.js project and deployed it to Vercel</p>
</li>
<li><p>Linked the custom domain to Vercel</p>
</li>
<li><p>Created a very minimal page that includes light and dark modes, real-time GitHub stars, and social profiles</p>
</li>
<li><p>Integrated Substack email (it might be improved in the future, but for now it works)</p>
</li>
</ul>
<p>Thanks to AI's support, all this was done in just a few hours. It's incredible how AI can speed up the process if you know what you're doing but want it done quickly.</p>
<p>This is how it looks right now. It's pretty basic, and not much on it, but I will keep working on it.</p>
<h3 id="heading-whats-next">What's Next:</h3>
<ul>
<li><p>Add more sections</p>
</li>
<li><p>Promote the project</p>
</li>
<li><p>Send email updates</p>
</li>
<li><p>Create some live events about this</p>
</li>
</ul>
<p>Feel free to check the GitHub repository: <a target="_blank" href="https://github.com/FrancescoXX/rustcrab">Rustcrab GitHub Repository</a></p>
<h3 id="heading-why-all-of-this">Why All of This?</h3>
<p>Well, because this is basically what I have been doing every day for more than six months: checking @dailydotdev, organizing things, making private lists and notes, and so on. I think it's time for this project to be more open and accessible to everyone.</p>
<p>I will also create a separate channel on Discord for discussions.</p>
<p>If you are interested in this project, subscribe to the newsletter and star the repo (only two stars now).</p>
<p>I will update you in the next few days.</p>
<p>The project aims to make your life easier if you want to get involved with the Rust community, resources, and updates. Rust is not for everyone, but if you want to make a bet on the future of your tech career, this is a great opportunity to stop making excuses and get started.</p>
<h3 id="heading-disclaimer">Disclaimer</h3>
<p>For now, it's not even worth checking, but I've learned that the sooner you launch, the better. Feel free to add issues in the GitHub repository, and I will work on that. I can also do some work live.</p>
<p>Well, that was a long post.</p>
<p>If you reached the end, that already means a lot to me.</p>
<p>Thank you</p>
<p>Check the project: <a target="_blank" href="https://www.rustcrab.com">Rustcrab</a></p>
]]></content:encoded></item><item><title><![CDATA[unwrap_or_else in Rust]]></title><description><![CDATA[The unwrap_or_else method is used as an Option or Result type.
Let's see an example for both.

unwrap_or_else on an Option
For Option, the unwrap_or_else method is used to provide a fallback value if the Option is None**
fn main() {
    let some_valu...]]></description><link>https://blog.francescociulla.com/unwraporelse-in-rust</link><guid isPermaLink="true">https://blog.francescociulla.com/unwraporelse-in-rust</guid><category><![CDATA[Rust]]></category><category><![CDATA[Rust programming]]></category><category><![CDATA[rust lang]]></category><category><![CDATA[rustseries]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Sat, 08 Jun 2024 08:33:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717835544762/298604da-4cb2-44f1-938f-5ce8332bdd27.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The <strong>unwrap_or_else</strong> method is used as an <strong>Option</strong> or <strong>Result</strong> type.</p>
<p>Let's see an example for both.</p>
<hr />
<h2 id="heading-unwraporelse-on-an-option">unwrap_or_else on an Option</h2>
<p>For <strong>Option</strong>, the <strong>unwrap_or_else</strong> method is used to provide a fallback value if the <strong>Option</strong> is None**</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> some_value: <span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">i32</span>&gt; = <span class="hljs-literal">Some</span>(<span class="hljs-number">10</span>);
    <span class="hljs-keyword">let</span> none_value: <span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">i32</span>&gt; = <span class="hljs-literal">None</span>;

    <span class="hljs-comment">// Using unwrap_or_else on an Option</span>
    <span class="hljs-keyword">let</span> result_some = some_value.unwrap_or_else(|| {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"some_value was None, using default value."</span>);
        <span class="hljs-number">0</span> <span class="hljs-comment">// Default value</span>
    });

    <span class="hljs-keyword">let</span> result_none = none_value.unwrap_or_else(|| {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"none_value was None, using default value."</span>);
        <span class="hljs-number">0</span> <span class="hljs-comment">// Default value</span>
    });

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Result when Option is Some: {}"</span>, result_some);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Result when Option is None: {}"</span>, result_none);
}
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">none_value was None, using default value.
Result when Option is Some: 10
Result when Option is None: 0
</code></pre>
<p>Explanation:</p>
<p>In this example, we have two <strong>Option</strong> variables, <strong>some_value</strong> and <strong>none_value</strong>. The <strong>some_value</strong> is <strong>Some(10)</strong> and the <strong>none_value</strong> is <strong>None</strong>.</p>
<p>The <strong>unwrap_or_else</strong> method is used on both <strong>Option</strong> variables. The closure passed to <strong>unwrap_or_else</strong> is only called when the <strong>Option</strong> is <strong>None</strong>. In this case, the closure prints a message and returns a default value of 0.</p>
<hr />
<h2 id="heading-unwraporelse-on-a-result">unwrap_or_else on a Result</h2>
<p>For <strong>Result</strong>, the <strong>unwrap_or_else</strong> method is used to provide a fallback value if the <strong>Result</strong> is an <strong>Err</strong>.</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> ok_result: <span class="hljs-built_in">Result</span>&lt;<span class="hljs-built_in">i32</span>, &amp;<span class="hljs-built_in">str</span>&gt; = <span class="hljs-literal">Ok</span>(<span class="hljs-number">10</span>);
    <span class="hljs-keyword">let</span> err_result: <span class="hljs-built_in">Result</span>&lt;<span class="hljs-built_in">i32</span>, &amp;<span class="hljs-built_in">str</span>&gt; = <span class="hljs-literal">Err</span>(<span class="hljs-string">"An error occurred"</span>);

    <span class="hljs-comment">// Using unwrap_or_else on a Result</span>
    <span class="hljs-keyword">let</span> result_ok = ok_result.unwrap_or_else(|err| {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"ok_result was Err: {}, using default value."</span>, err);
        <span class="hljs-number">0</span> <span class="hljs-comment">// Default value</span>
    });

    <span class="hljs-keyword">let</span> result_err = err_result.unwrap_or_else(|err| {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"err_result was Err: {}, using default value."</span>, err);
        <span class="hljs-number">0</span> <span class="hljs-comment">// Default value</span>
    });

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Result when Result is Ok: {}"</span>, result_ok);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Result when Result is Err: {}"</span>, result_err);
}
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Error: Error message
Result when Result is Ok: 10
Result when Result is Err: 0
</code></pre>
<p>Explanation:</p>
<p>In this example, we have two <strong>Result</strong> variables, <strong>ok_result</strong> and <strong>err_result</strong>. The <strong>ok_result</strong> is <strong>Ok(10)</strong> and the <strong>err_result</strong> is <strong>Err("An error occurred")</strong>.</p>
<p>The <strong>unwrap_or_else</strong> method is used on both <strong>Result</strong> variables. The closure passed to <strong>unwrap_or_else</strong> is only called when the <strong>Result</strong> is <strong>Err</strong>. In this case, the closure prints a message and returns a default value of 0.</p>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>In both examples, the <strong>unwrap_or_else</strong> method is used to provide a default value when the <strong>Option</strong> or <strong>Result</strong> is <strong>None</strong> or <strong>Err</strong> respectively.</p>
<p>The <strong>unwrap_or_else</strong> method takes a closure that returns the default value. The closure is only called when the <strong>Option</strong> is <strong>None</strong> or the <strong>Result</strong> is <strong>Err</strong>.</p>
<p>If you find this interesting and you want to get started with Rust, you can check this <a target="_blank" href="https://www.youtube.com/watch?v=R33h77nrMqc&amp;list=PLPoSdR46FgI412aItyJhj2bF66cudB6Qs&amp;index=1&amp;ab_channel=FrancescoCiulla">FREE playlist on YouTube</a>:</p>
]]></content:encoded></item><item><title><![CDATA[Structs in Rust]]></title><description><![CDATA[In this lesson, we will talk about Structs in Rust
What are Structs?
Structs are a way to create more complex data types. 
They are similar to tuples, but with a few differences. 
For example, you can name the fields of a struct (and you can also def...]]></description><link>https://blog.francescociulla.com/structs-in-rust</link><guid isPermaLink="true">https://blog.francescociulla.com/structs-in-rust</guid><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Tue, 12 Mar 2024 14:14:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1710252811900/c3d2ec89-1ceb-42ea-bab2-890d5cdca2f6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this lesson, we will talk about Structs in Rust</p>
<h2 id="heading-what-are-structs">What are Structs?</h2>
<p>Structs are a way to create more complex data types. </p>
<p>They are similar to tuples, but with a few differences. </p>
<p>For example, you can name the fields of a struct (and you can also define methods for structs).</p>
<p>If you prefer a video version</p>
<iframe width="905" height="510" src="https://www.youtube.com/embed/PCjuO-Bv5FI"></iframe>

<p>All the code is available on <a target="_blank" href="https://youtu.be/PCjuO-Bv5FI">GitHub</a> (link available in the video description)</p>
<h2 id="heading-define-a-struct">Define a Struct</h2>
<p>Let's say that we want to crete a User, with name, email, is_active and age. We can define a struct like this:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">User</span></span> {
    name: <span class="hljs-built_in">String</span>,
    email: <span class="hljs-built_in">String</span>,
    is_active: <span class="hljs-built_in">bool</span>,
    age: <span class="hljs-built_in">u8</span>,
}

And then you can create an instance of the <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">like</span></span> this:

```rust
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">User</span></span> {
    name: <span class="hljs-built_in">String</span>,
    email: <span class="hljs-built_in">String</span>,
    is_active: <span class="hljs-built_in">bool</span>,
    age: <span class="hljs-built_in">u8</span>,
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> user = User {
        name: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Jhon Doe"</span>),
        email: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"doe@mail.com"</span>),
        is_active: <span class="hljs-literal">true</span>,
        age: <span class="hljs-number">25</span>,
    };
}
</code></pre>
<h2 id="heading-accessing-struct-fields">Accessing Struct Fields</h2>
<p>You can access the fields of a struct using dot notation:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">User</span></span> {
    name: <span class="hljs-built_in">String</span>,
    email: <span class="hljs-built_in">String</span>,
    is_active: <span class="hljs-built_in">bool</span>,
    age: <span class="hljs-built_in">u8</span>,
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> user = User {
        name: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Jhon Doe"</span>),
        email: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"doe@mail.com"</span>),
        is_active: <span class="hljs-literal">true</span>,
        age: <span class="hljs-number">25</span>,
    };

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"User name: {}"</span>, user.name);
}
</code></pre>
<p>Explanaition:</p>
<ul>
<li>We define a struct called User with four fields: name, email, is_active and age.</li>
<li>We create an instance of the struct and assign it to the user variable.</li>
<li>We access the name field of the user struct using dot notation (user.name).</li>
</ul>
<p><a target="_blank" href="https://youtu.be/PCjuO-Bv5FI"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p8ftlzr2b3kmjc94d05x.png" alt="Structs in Rust - Rust programming tutorial" /></a></p>
<h2 id="heading-mutable-structs">Mutable Structs</h2>
<p>You can make a struct mutable by using the mut keyword:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">User</span></span> {
    name: <span class="hljs-built_in">String</span>,
    email: <span class="hljs-built_in">String</span>,
    is_active: <span class="hljs-built_in">bool</span>,
    age: <span class="hljs-built_in">u8</span>,
}

<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> user = User {
        name: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Jhon Doe"</span>),
        email: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"doe@mail.com"</span>),
        is_active: <span class="hljs-literal">true</span>,
        age: <span class="hljs-number">25</span>,
    };

    user.name = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Francesco"</span>);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"User name: {}"</span>, user.name);

}
</code></pre>
<p><a target="_blank" href="https://youtu.be/PCjuO-Bv5FI"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o0d3ealwd1pabinrls47.png" alt="Structs in Rust - Rust programming tutorial" /></a></p>
<p>Note the you can't make individual fields of a struct mutable, you can only make the entire struct mutable.</p>
<h2 id="heading-create-a-struct-instance-using-a-function">Create a Struct instance using a function</h2>
<p>You can create a function that returns a struct instance:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">User</span></span> {
    name: <span class="hljs-built_in">String</span>,
    email: <span class="hljs-built_in">String</span>,
    is_active: <span class="hljs-built_in">bool</span>,
    age: <span class="hljs-built_in">u8</span>,
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> user = create_user(<span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Jhon Doe"</span>), <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"doe@mail"</span>),);

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"User name: {}"</span>, user.name);
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">create_user</span></span>(name: <span class="hljs-built_in">String</span>, email: <span class="hljs-built_in">String</span>,) -&gt; User {
    User {
        name,
        email,
        is_active: <span class="hljs-literal">true</span>,
        age : <span class="hljs-number">25</span>,
    }
}
</code></pre>
<p>You can see the init shorthand syntax in the create_user function. This is a shorthand for initializing fields with variables that have the same name as the fields.</p>
<p><a target="_blank" href="https://youtu.be/PCjuO-Bv5FI"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l69dzuu8lyl4mxo5ubxf.png" alt="Structs in Rust - Rust programming tutorial" /></a></p>
<h2 id="heading-creating-instances-from-other-instances-with-struct-update-syntax">Creating Instances from Other Instances with Struct Update Syntax</h2>
<p>You can create a new instance of a struct using another instance with the struct update syntax:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">User</span></span> {
    name: <span class="hljs-built_in">String</span>,
    email: <span class="hljs-built_in">String</span>,
    is_active: <span class="hljs-built_in">bool</span>,
    age: <span class="hljs-built_in">u8</span>,
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> user1 = User {
        name: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Jhon Doe"</span>),
        email: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"doe@mail.com"</span>),
        is_active: <span class="hljs-literal">false</span>,
        age: <span class="hljs-number">40</span>
    };

    <span class="hljs-keyword">let</span> new_user = User {
        name: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Francesco"</span>),
        email: user1.email,
        is_active: user1.is_active,
        age: user1.age,
    };

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"User name: {}"</span>, new_user.name);
}
</code></pre>
<p>In this example, we create a new instance of the User struct using the user1 instance with the struct update syntax.</p>
<p><a target="_blank" href="https://youtu.be/PCjuO-Bv5FI"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/28qkv2lwc0fdkyxqbuzd.png" alt="Structs in Rust - Rust programming tutorial" /></a></p>
<h2 id="heading-tuple-structs">Tuple Structs</h2>
<p>Tuple structs are similar to regular structs, but their fields are not named:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Color</span></span>(<span class="hljs-built_in">i32</span>, <span class="hljs-built_in">i32</span>, <span class="hljs-built_in">i32</span>);
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Point</span></span>(<span class="hljs-built_in">i32</span>, <span class="hljs-built_in">i32</span>, <span class="hljs-built_in">i32</span>);

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> black = Color(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>);
    <span class="hljs-keyword">let</span> origin = Point(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Black color: {}, {}, {}"</span>, black.<span class="hljs-number">0</span>, black.<span class="hljs-number">1</span>, black.<span class="hljs-number">2</span>);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Origin: {}, {}, {}"</span>, origin.<span class="hljs-number">0</span>, origin.<span class="hljs-number">1</span>, origin.<span class="hljs-number">2</span>);
}
</code></pre>
<p>In this example, we define two tuple structs: Color and Point. We create instances of these tuple structs and access their fields using dot notation.</p>
<p><a target="_blank" href="https://youtu.be/PCjuO-Bv5FI"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/itkr4dg71exrfdes91fs.png" alt="Structs in Rust - Rust programming tutorial" /></a></p>
<h2 id="heading-unit-like-structs">Unit-Like Structs</h2>
<p>You can define a struct with no fields, called a unit-like struct:</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">User</span></span>;

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> user = User;
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"User: {:?}"</span>, user);
}
</code></pre>
<p>Unit-like structs are useful when you need to implement a trait on a type but don't have any data to store in the type.</p>
<p><a target="_blank" href="https://youtu.be/PCjuO-Bv5FI"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1rn23cig9vdd1armfg13.png" alt="Structs in Rust - Rust programming tutorial" /></a></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Structs are a way to create more complex data types in Rust. They are similar to tuples, but with a few differences. You can name the fields of a struct (and you can also define methods for structs). You can also make a struct mutable by using the mut keyword. </p>
<p>You can create a function that returns a struct instance. You can create a new instance of a struct using another instance with the struct update syntax. You can define tuple structs and unit-like structs.</p>
<p>I hope this lesson was useful. In the next lesson, we will see a practical example of using structs in Rust.</p>
<p>If you prefer a video version</p>
<iframe width="905" height="510" src="https://www.youtube.com/embed/PCjuO-Bv5FI"></iframe>

<p>All the code is available on <a target="_blank" href="https://youtu.be/PCjuO-Bv5FI">GitHub</a> (link available in the video description)</p>
<p>You can find me on https://francescociulla.com and on <a target="_blank" href="https://twitter.com/FrancescoCiull4">Twitter/X</a></p>
]]></content:encoded></item><item><title><![CDATA[Slices in Rust]]></title><description><![CDATA[The Slice type in Rust
Rust has a built-in type called Slice that is used to reference a contiguous sequence of elements in a collection. Slices are a very important concept in Rust, and they are used extensively in the standard library. In this less...]]></description><link>https://blog.francescociulla.com/slices-in-rust</link><guid isPermaLink="true">https://blog.francescociulla.com/slices-in-rust</guid><category><![CDATA[Rust]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Tue, 05 Mar 2024 14:14:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1709647941651/2990d160-0e36-4181-a860-f261393809b3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-the-slice-type-in-rust">The Slice type in Rust</h2>
<p>Rust has a built-in type called <code>Slice</code> that is used to reference a contiguous sequence of elements in a collection. Slices are a very important concept in Rust, and they are used extensively in the standard library. In this lesson, we will explore the <code>Slice</code> type and how it is used in Rust.</p>
<p>If you prefer a video version</p>
<iframe width="905" height="510" src="https://www.youtube.com/embed/dKymZbFp0ZQ"></iframe>

<p>All the code is available on <a target="_blank" href="https://youtu.be/dKymZbFp0ZQ">GitHub</a> (link available in the video description)</p>
<h2 id="heading-what-is-a-slice">What is a Slice?</h2>
<p>A slice is a reference to a contiguous sequence of elements in a collection. </p>
<p>Slices are used to reference a portion of a collection, and they are used extensively in the standard library. </p>
<p>Slices are a very important concept in Rust, and they are used extensively in the standard library. In this lesson, we will explore the <code>Slice</code> type and how it is used in Rust.</p>
<h2 id="heading-a-first-example">A first example</h2>
<p>Let's see a simple example of a slice. We will use an array:</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> a = [<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"c"</span>, <span class="hljs-string">"d"</span>, <span class="hljs-string">"e"</span>];
    <span class="hljs-keyword">let</span> slice = &amp;a[<span class="hljs-number">1</span>..<span class="hljs-number">3</span>];
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, slice);
}
</code></pre>
<p>In this example, we have an array <code>a</code> with five elements. We then create a slice <code>slice</code> that references the second and third elements of the array.</p>
<p>When we run the program, we get the following output:</p>
<pre><code class="lang-rust">[<span class="hljs-string">"b"</span>, <span class="hljs-string">"c"</span>]
</code></pre>
<p>The Range <code>1..3</code> is used to create the slice. The first number is the starting index, and the second number is the ending index. </p>
<p>The ending index is exclusive, which means that the element at the ending index is not included in the slice.</p>
<h2 id="heading-a-second-example">A second example</h2>
<p>Let's try a slice of a vector of integers:</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> v = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>, <span class="hljs-number">50</span>];
    <span class="hljs-keyword">let</span> slice = &amp;v[<span class="hljs-number">3</span>..<span class="hljs-number">4</span>];
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, slice);
}
</code></pre>
<p>In this example, we have a vector <code>v</code> with five elements. We then create a slice <code>slice</code> that references the fourth element of the vector.</p>
<p>When we run the program, we get the following output:</p>
<pre><code class="lang-rust">[<span class="hljs-number">40</span>]
</code></pre>
<h2 id="heading-third-example">Third Example</h2>
<p>Let's try a slice of a string:</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> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello world"</span>);
    <span class="hljs-keyword">let</span> hello = &amp;s[<span class="hljs-number">0</span>..<span class="hljs-number">5</span>];
    <span class="hljs-keyword">let</span> world = &amp;s[<span class="hljs-number">6</span>..<span class="hljs-number">11</span>];
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, hello);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, world);
}
</code></pre>
<p>In this example, we have a string <code>s</code> with the value "hello world". We then create two slices, <code>hello</code> and <code>world</code>, that reference the first five and last five characters of the string, respectively.</p>
<p>When we run the program, we get the following output:</p>
<pre><code class="lang-rust"><span class="hljs-string">"hello"</span>
<span class="hljs-string">"world"</span>
</code></pre>
<p><a target="_blank" href="https://youtu.be/dKymZbFp0ZQ"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/895gl86olb3thkleo78o.png" alt="Slices in Rust - Rust programming tutorial" /></a></p>
<h2 id="heading-range-shortcuts-for-slices">Range shortcuts for slices</h2>
<p>There are some shortcuts for creating slices. For example, if you want to start at index 0, you can omit the first number:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);
<span class="hljs-keyword">let</span> slice = &amp;s[<span class="hljs-number">0</span>..<span class="hljs-number">2</span>];
<span class="hljs-keyword">let</span> slice = &amp;s[..<span class="hljs-number">2</span>];
</code></pre>
<p>Will have as an output:</p>
<pre><code class="lang-rust"><span class="hljs-string">"he"</span>
</code></pre>
<p>Also, if you want to go to the end of the string, you can omit the second number:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);
<span class="hljs-keyword">let</span> len = s.len();
<span class="hljs-keyword">let</span> slice = &amp;s[<span class="hljs-number">3</span>..len];
<span class="hljs-keyword">let</span> slice = &amp;s[<span class="hljs-number">3</span>..];
</code></pre>
<p>Will have as an output:</p>
<pre><code class="lang-rust"><span class="hljs-string">"lo"</span>
</code></pre>
<p>You can also get the entire string by using the <code>..</code> syntax:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);
<span class="hljs-keyword">let</span> len = s.len();
<span class="hljs-keyword">let</span> slice = &amp;s[<span class="hljs-number">0</span>..len];
<span class="hljs-keyword">let</span> slice = &amp;s[..];
</code></pre>
<p>Will have as an output:</p>
<pre><code class="lang-rust"><span class="hljs-string">"hello"</span>
</code></pre>
<h2 id="heading-exercise-without-slices">Exercise (without Slices)</h2>
<p>Let's write a program that takes a string and returns the first word in the string. </p>
<p>First, let'simplement a solution without using slices.</p>
<p>Here is the 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> <span class="hljs-keyword">mut</span> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello world"</span>);
    <span class="hljs-keyword">let</span> word = first_word(&amp;s);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"the first word is: {}"</span>, word);
}


<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">first_word</span></span>(s: &amp;<span class="hljs-built_in">String</span>) -&gt; <span class="hljs-built_in">usize</span> {
    <span class="hljs-keyword">let</span> bytes = s.as_bytes();

    <span class="hljs-keyword">for</span> (i, &amp;item) <span class="hljs-keyword">in</span> bytes.iter().enumerate() {
        <span class="hljs-keyword">if</span> item == <span class="hljs-string">b' '</span> {
            <span class="hljs-keyword">return</span> i;
        }
    }

    s.len()
}
</code></pre>
<p>Explanation:</p>
<ul>
<li>The <code>as_bytes</code> method returns a slice of the string's bytes.</li>
<li>The <code>iter</code> method returns an iterator over the slice.</li>
<li>The <code>enumerate</code> method returns an iterator that yields the index and the value of each element in the slice.</li>
<li>The <code>b' '</code> syntax is used to create a byte literal.</li>
<li>The <code>s.len()</code> method returns the length of the string.</li>
</ul>
<p>We get this output:</p>
<pre><code class="lang-rust">the first word is: <span class="hljs-number">5</span>
</code></pre>
<p>In  this case, <code>5</code> is the index of the first space in the string, which is the end of the first word.</p>
<p>But there is a problem with this code. If we try to clear the string <code>s</code> after calling the <code>first_word</code> function, we will NOT get a compile error. The variable <code>word</code> will still have the value 5, even though the string <code>s</code> has been cleared.</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> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello world"</span>);
    <span class="hljs-keyword">let</span> word = first_word(&amp;s); <span class="hljs-comment">// word will get the value 5</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"the s is: {}"</span>, s);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"the first word is: {}"</span>, word);

    s.clear(); <span class="hljs-comment">// this empties the String, making it equal to ""</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"the s is: {}"</span>, s);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"the first word is: {}"</span>, word);    
}
</code></pre>
<p>The output will be:</p>
<pre><code class="lang-rust">the s is: hello world
the first word is: <span class="hljs-number">5</span>
the s is:
the first word is: <span class="hljs-number">5</span>
</code></pre>
<p>The <code>word</code> variable still has the value 5, but the string <code>s</code> has been cleared. </p>
<p>Let's see how we can fix this using slices.</p>
<h2 id="heading-exercise-using-slices">Exercise (using slices)</h2>
<p>Let's go back to our programming example.</p>
<p>Using slices, we can rewrite the <code>first_word</code> function like this:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">first_word</span></span>(s: &amp;<span class="hljs-built_in">String</span>) -&gt; &amp;<span class="hljs-built_in">str</span> {
    <span class="hljs-keyword">let</span> bytes = s.as_bytes();

    <span class="hljs-keyword">for</span> (i, &amp;item) <span class="hljs-keyword">in</span> bytes.iter().enumerate() {
        <span class="hljs-keyword">if</span> item == <span class="hljs-string">b' '</span> {
            <span class="hljs-keyword">return</span> &amp;s[<span class="hljs-number">0</span>..i];
        }
    }

    &amp;s[..]
}
</code></pre>
<p>Now, the <code>first_word</code> function returns a string slice, which is a reference to part of the original string. </p>
<p>If now we have somerthing like this:</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> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello world"</span>);
    <span class="hljs-keyword">let</span> word = first_word(&amp;s); <span class="hljs-comment">// word will get the value 5</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"the s is: {}"</span>, s);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"the first word is: {}"</span>, word);

    s.clear(); <span class="hljs-comment">// this empties the String, making it equal to ""</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"the s is: {}"</span>, s);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"the first word is: {}"</span>, word);    
}
</code></pre>
<p>We will get a compile error, because we are trying to use <code>word</code> after <code>s</code> has been cleared.</p>
<h2 id="heading-string-literals-as-slices">String literals as Slices</h2>
<p>Recall that we talked about string literals being stored inside the binary.</p>
<p>Now that we know about slices, we can understand string literals.</p>
<p>Update the code in the <code>main</code> function to use a string literal below the <code>s</code> variable (you can keep the lines that use <code>s</code> as well). :</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> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello world"</span>);
    <span class="hljs-keyword">let</span> word = first_word(&amp;s); <span class="hljs-comment">// word will get the value 5</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"the s is: {}"</span>, s);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"the first word is: {}"</span>, word);

    <span class="hljs-keyword">let</span> s2 = <span class="hljs-string">"hello world"</span>;
    <span class="hljs-keyword">let</span> word2 = first_word(&amp;s2); <span class="hljs-comment">// word will get the value 5</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"the s is: {}"</span>, s2);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"the first word is: {}"</span>, word2);
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">first_word</span></span>(s: &amp;<span class="hljs-built_in">str</span>) -&gt; &amp;<span class="hljs-built_in">str</span> {
    <span class="hljs-keyword">let</span> bytes = s.as_bytes();

    <span class="hljs-keyword">for</span> (i, &amp;item) <span class="hljs-keyword">in</span> bytes.iter().enumerate() {
        <span class="hljs-keyword">if</span> item == <span class="hljs-string">b' '</span> {
            <span class="hljs-keyword">return</span> &amp;s[<span class="hljs-number">0</span>..i];
        }
    }

    &amp;s[..]
}
</code></pre>
<p>The type of <code>s</code> is <code>&amp;str</code>, which is a slice of a string. This means that <code>s</code> is a reference to a contiguous sequence of characters in memory.</p>
<p>As a final note, the type of <code>s2</code> is <code>&amp;str</code>, which is a slice of a string. This means that <code>s2</code> is a reference to a contiguous sequence of characters in memory.</p>
<p>So we can remove the <code>&amp;s2</code> from the <code>first_word</code> function and the code will still work.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this lesson, we explored the <code>Slice</code> type in Rust. We learned that a slice is a reference to a contiguous sequence of elements in a collection. </p>
<p>We also learned how to create slices using the <code>Range</code> type and how to use slices to reference parts of a string.</p>
<p>In the next lesson, we will see the <code>Struct</code> type in Rust.</p>
<p>If you prefer a video version</p>
<iframe width="905" height="510" src="https://www.youtube.com/embed/dKymZbFp0ZQ"></iframe>

<p>All the code is available on <a target="_blank" href="https://youtu.be/dKymZbFp0ZQ">GitHub</a> (link available in the video description)</p>
]]></content:encoded></item><item><title><![CDATA[References and Borrowing in Rust]]></title><description><![CDATA[References and Borrowing
In this article, we will see how to use references in Rust. If you want an introduction to Ownership in Rust, in can check the previous article
In this lesson, we will see:

Ownership and Functions
Return Values and Scope
Int...]]></description><link>https://blog.francescociulla.com/references-and-borrowing-in-rust</link><guid isPermaLink="true">https://blog.francescociulla.com/references-and-borrowing-in-rust</guid><category><![CDATA[Rust]]></category><category><![CDATA[software development]]></category><category><![CDATA[Developer]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Francesco Ciulla]]></dc:creator><pubDate>Tue, 27 Feb 2024 14:07:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1709042785702/08aeb001-b462-49cf-befc-0408b8de756d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-references-and-borrowing">References and Borrowing</h2>
<p>In this article, we will see how to use references in Rust. If you want an introduction to Ownership in Rust, in can check the <a target="_blank" href="https://dev.to/francescoxx/ownership-in-rust-57j2">previous article</a></p>
<p>In this lesson, we will see:</p>
<ul>
<li>Ownership and Functions</li>
<li>Return Values and Scope</li>
<li>Introduction to References and Borrowing</li>
<li>Mutable References</li>
<li>Multiple Mutable References</li>
<li>Mutable and Immutable References</li>
<li>Dangling references</li>
<li>References Rules</li>
</ul>
<p>If you prefer a video version</p>
<iframe width="905" height="510" src="https://www.youtube.com/embed/Q_0yoX07Fhs"></iframe>

<p>All the code is available on <a target="_blank" href="https://youtu.be/Q_0yoX07Fhs">GitHub</a> (link available in the video description)</p>
<h2 id="heading-ownership-and-functions">Ownership and Functions</h2>
<p>When you pass a variable to a function, you move or copy it. </p>
<p>If you move it, as it happens with strings, the variable is no longer valid after the function call.</p>
<pre><code class="lang-rust"><span class="hljs-comment">//ownership and functions</span>
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>(){
    <span class="hljs-keyword">let</span> i = <span class="hljs-number">5</span>;
    call_integer(i);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, i);

    <span class="hljs-keyword">let</span> s = <span class="hljs-built_in">String</span>::from (<span class="hljs-string">"Hello, World!"</span>);
    call_string(s);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, s);
}
</code></pre>
<p><a target="_blank" href="https://youtu.be/Q_0yoX07Fhs"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wftpe5htx7ylrrm428bp.png" alt="References and borrowing" /></a></p>
<h2 id="heading-return-values-and-scope">Return Values and Scope</h2>
<p>When a function returns a value, it gives ownership of the value to the calling function. </p>
<p>We can also have a function that has ownership but gives it back to the calling function. </p>
<pre><code class="lang-rust"><span class="hljs-comment">//ownership and functions</span>
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>(){
    <span class="hljs-keyword">let</span> s1 = give_ownership();
    <span class="hljs-keyword">let</span> s2 = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);  <span class="hljs-comment">// s2 comes into scope</span>
    <span class="hljs-keyword">let</span> s3 = take_and_give_back(s2); <span class="hljs-comment">// s2 is moved into take_and_give_back, it returns s3</span>

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"s1: {}"</span>, s1);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"s2: {}"</span>, s2); <span class="hljs-comment">// error: value used here after move</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"s3: {}"</span>, s3);
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">give_ownership</span></span>() -&gt; <span class="hljs-built_in">String</span> {
    <span class="hljs-keyword">let</span> some_string = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);
    some_string
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">take_and_give_back</span></span>(a_string: <span class="hljs-built_in">String</span>) -&gt; <span class="hljs-built_in">String</span> {
    a_string
}
</code></pre>
<p>Let's type <code>cargo run -q</code> and see the output:</p>
<p><a target="_blank" href="https://youtu.be/Q_0yoX07Fhs"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cbw8upxwx1kjnvx7dx3e.png" alt="References and borrowing" /></a></p>
<p>But if we try to use the <code>s2</code> variable after the function call, we get an error. </p>
<p><a target="_blank" href="https://youtu.be/Q_0yoX07Fhs"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eoiezwv9xk5i6sapox5o.png" alt="References and borrowing" /></a></p>
<p>So how can we solve this? Let's see an example.</p>
<h3 id="heading-a-first-example-of-getting-the-ownership-back">A first example of getting the ownership back</h3>
<p>One first solution might be this: we can return the value passed in input back, using a tuple.</p>
<p>For example, if we want to calculate the length of a string, we can return the string and its length. </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> s1 = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);
    <span class="hljs-keyword">let</span> (s2, len) = calculate_length(s1);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"The length of '{}' is {}"</span>, s2, len);
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">calculate_length</span></span>(s: <span class="hljs-built_in">String</span>) -&gt; (<span class="hljs-built_in">String</span>, <span class="hljs-built_in">usize</span>){
    <span class="hljs-keyword">let</span> length = s.len();
    (s, length)
}
</code></pre>
<p>This "works", but it's not the best solution.</p>
<p><a target="_blank" href="https://youtu.be/Q_0yoX07Fhs"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gksowco1ua3l7062frmz.png" alt="References and borrowing" /></a></p>
<p>This solution is tedious and error-prone. </p>
<p>Rust has a feature called references that allows you to refer to some value without taking ownership of it. </p>
<p>Let's see how to modify the previous example using references.</p>
<h2 id="heading-introduction-to-references-and-borrowing">Introduction to References and Borrowing</h2>
<p>Modify the code above to use references instead of taking ownership of the string. </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> s1 = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);
    <span class="hljs-keyword">let</span> len = calculate_length(&amp;s1);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"The length of '{}' is {}"</span>, s1, len);
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">calculate_length</span></span>(s: &amp;<span class="hljs-built_in">String</span>) -&gt; <span class="hljs-built_in">usize</span>{
    <span class="hljs-keyword">let</span> length = s.len();
    length
}
</code></pre>
<p>Explanation:  <code>&amp;s1</code> creates a reference to the value of <code>s1</code> but does not take ownership of it.</p>
<p>In the signature of <code>calculate_length</code>, <code>s: &amp;String</code> means that <code>s</code> is a reference to a <code>String</code>.</p>
<p>If we type <code>cargo run -q</code>, we get the expected output:</p>
<p><a target="_blank" href="https://youtu.be/Q_0yoX07Fhs"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bvag6sg7tw2ae0nld8pe.png" alt="References and borrowing" /></a></p>
<p>We are getting the same outut as before, but now we are not taking ownership of the string.</p>
<p>Here is a schema of what happens when we pass a reference to a function:</p>
<p><a target="_blank" href="https://youtu.be/Q_0yoX07Fhs"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5h98ihajfjfsrci7zwju.png" alt="References and borrowing" /></a></p>
<p>IMPORTANT: The action of passing a reference to a function is called <code>Borrowing</code>.</p>
<h2 id="heading-mutable-references">Mutable References</h2>
<p>Can we change the value of a reference? </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> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);
    change(&amp;s);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, s);
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">change</span></span>(s: &amp;<span class="hljs-built_in">String</span>){
    s.push_str(<span class="hljs-string">", world"</span>);
}
</code></pre>
<p>But here we get an error:</p>
<p><a target="_blank" href="https://youtu.be/Q_0yoX07Fhs"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z9oz1ds0utqkoat4jvtq.png" alt="References and borrowing" /></a></p>
<p>References are immutable by default.</p>
<p>But we can make them mutable by using <code>&amp;mut</code> instead of <code>&amp;</code>.</p>
<p>Of course, the value of the variable must be mutable as well.</p>
<pre><code class="lang-rust"><span class="hljs-comment">//mutable references</span>
<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> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);
    modify(&amp;<span class="hljs-keyword">mut</span> s);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, s);
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">modify</span></span>(s: &amp;<span class="hljs-keyword">mut</span> <span class="hljs-built_in">String</span>){
    s.push_str(<span class="hljs-string">" world"</span>);
}
</code></pre>
<h2 id="heading-multiple-mutable-references">Multiple Mutable References</h2>
<p>Can we have multiple mutable references to the same variable?</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> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);

    <span class="hljs-keyword">let</span> s1 = &amp;<span class="hljs-keyword">mut</span> s;
    <span class="hljs-keyword">let</span> s2 = &amp;<span class="hljs-keyword">mut</span> s;

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}, {}"</span>, s1, s2);
}
</code></pre>
<p>This code is not valid. </p>
<p><a target="_blank" href="https://youtu.be/Q_0yoX07Fhs"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/856dyqrppwq7qmsfg7g9.png" alt="References and borrowing" /></a></p>
<p>This should surprise you. In many programming languages, having multiple references to the same variable is not a problem. But this can lead to problems at runtime.</p>
<p>In Rust, the compiler prevents this from happening.</p>
<p>Of course, we can have multiple mutable references, but in different scopes.</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> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);

    {
        <span class="hljs-keyword">let</span> s1 = &amp;<span class="hljs-keyword">mut</span> s;
        s1.push_str(<span class="hljs-string">" world"</span>);
    }   <span class="hljs-comment">//s1 goes out of scope here</span>

    <span class="hljs-keyword">let</span> s2 = &amp;<span class="hljs-keyword">mut</span> s;
    s2.push_str(<span class="hljs-string">"!"</span>);

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, s2);
}
</code></pre>
<p>This code is valid.</p>
<h2 id="heading-mutable-and-immutable-references">Mutable and Immutable References</h2>
<p>Let's try to mix mutable and immutable references.</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> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);

    <span class="hljs-keyword">let</span> s1 = &amp;s; <span class="hljs-comment">//immutable borrow</span>
    <span class="hljs-keyword">let</span> s2 = &amp;s; <span class="hljs-comment">//immutable borrow</span>

    <span class="hljs-keyword">let</span> s3 = &amp;<span class="hljs-keyword">mut</span> s; <span class="hljs-comment">//mutable borrow</span>

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}, {}, {}"</span>, s1, s2, s3);
    <span class="hljs-comment">//throws error: cannot borrow `s` as mutable because it is also borrowed as immutable</span>
}
</code></pre>
<p>This code is not valid: we cannot have a mutable reference while we have immutable references.</p>
<p><a target="_blank" href="https://youtu.be/Q_0yoX07Fhs"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sehvgh8sk5x2n4a93wa2.png" alt="References and borrowing" /></a></p>
<p>But if we use the immutable references before the mutable reference, the code is valid.</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> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);

    <span class="hljs-keyword">let</span> s1 = &amp;s; <span class="hljs-comment">//immutable borrow</span>
    <span class="hljs-keyword">let</span> s2 = &amp;s; <span class="hljs-comment">//immutable borrow</span>

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{} and {}"</span>, s1, s2);

    <span class="hljs-keyword">let</span> s3 = &amp;<span class="hljs-keyword">mut</span> s; <span class="hljs-comment">//mutable borrow</span>

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, s3);
}
</code></pre>
<p>This code is valid because the immutable borrows are not used after the mutable borrow. </p>
<h2 id="heading-dangling-references">Dangling references</h2>
<p>A Dangling reference is a reference that points to an invalid memory.</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> s  = dangle();
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">dangle</span></span>() -&gt; &amp;<span class="hljs-built_in">String</span> {
    <span class="hljs-keyword">let</span> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);
    &amp;s
}
</code></pre>
<p>In this case, the reference <code>&amp;s</code> is returned, but <code>s</code> goes out of scope at the end of the function.</p>
<p><a target="_blank" href="https://youtu.be/Q_0yoX07Fhs"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oury4og6ym9l22evnloq.png" alt="References and borrowing" /></a></p>
<p>To solve this problem, we can return the string directly. </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> s = no_dangle();
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, s);
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">no_dangle</span></span>() -&gt; <span class="hljs-built_in">String</span> {
    <span class="hljs-keyword">let</span> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);
    s
}
</code></pre>
<p><a target="_blank" href="https://youtu.be/Q_0yoX07Fhs"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lp0pvla1psurxmhlnoxp.png" alt="References and borrowing" /></a></p>
<p>This code is valid.</p>
<h2 id="heading-references-rules">References Rules</h2>
<p>There are 2 main rules for references:</p>
<ul>
<li><p>At any given time, you can have either one mutable reference or any number of immutable references.</p>
</li>
<li><p>References must always be valid.</p>
</li>
</ul>
<p><a target="_blank" href="https://youtu.be/Q_0yoX07Fhs"><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e18qhylnq94bqqns6dno.png" alt="References and borrowing" /></a></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we have seen how to use references in Rust.</p>
<p>We have seen how to pass references to functions, how to use mutable references, and the rules for using references.</p>
<p>If you prefer a video version</p>
<iframe width="905" height="510" src="https://www.youtube.com/embed/Q_0yoX07Fhs"></iframe>

<p>All the code is available on <a target="_blank" href="https://youtu.be/Q_0yoX07Fhs">GitHub</a> (link available in the video description)</p>
<p>You can find me here: <a target="_blank" href="https://francescociulla.com">Francesco</a></p>
]]></content:encoded></item></channel></rss>