<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Oduah Chigozie - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Oduah Chigozie - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 16:29:51 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/GhoulKingR/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ What are Smart Pointers in Rust? Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Smart pointers are data structures that act like pointers but contain extra information and have functionalities that make them excel over regular pointers in certain situations. So what are regular pointers? Regular pointers (just called “pointers”)... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/smart-pointers-in-rust-with-code-examples/</link>
                <guid isPermaLink="false">6721aeb8d9c3d37db41183a6</guid>
                
                    <category>
                        <![CDATA[ Rust ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oduah Chigozie ]]>
                </dc:creator>
                <pubDate>Wed, 30 Oct 2024 03:57:44 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730260779440/3d82425c-fdff-4a17-bb88-8193d964e6ba.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Smart pointers are data structures that act like pointers but contain extra information and have functionalities that make them excel over regular pointers in certain situations.</p>
<p>So what are regular pointers? Regular pointers (just called “pointers”) are variables that hold memory addresses as their values. They allow programs to store, read, and write data to memory locations with their addresses.</p>
<p>Here’s a diagram to give an idea of what they are:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730198558597/cd21ca42-32bb-4b41-98d3-b30956a6a398.png" alt="Diagram showing a table of variables and memory addresses. &quot;Text&quot; and &quot;Name&quot; are pointers that hold addresses 0x80012 and 0x80018 respectively" class="image--center mx-auto" width="2381" height="1632" loading="lazy"></p>
<p>In programming languages like C, C++, and Rust, pointers are useful for accessing manually allocated memory, but they come with these limitations:</p>
<ul>
<li><p>The memory address that a pointer holds can be deallocated while the pointer still references it, making it a dangling pointer.</p>
</li>
<li><p>The pointer doesn’t help with managing the memory allocation, which can cause memory leaks or other types of memory bugs in cases where handling memory allocations are complex.</p>
</li>
</ul>
<p>Rust doesn’t give the same level of control of pointers as with C and C++. However, like C++, Rust provides smart pointers that overcome the limitations of regular pointers while providing extra functionalities.</p>
<p>In Rust, there are four major types of smart pointers: <code>Box</code>, <code>Rc</code>, <code>Arc</code>, and <code>Weak</code>. I’ll be discussing them in this article. I’ll also touch a little on <code>RefCell</code>, because it adds a specific functionality that is missing in other smart pointers.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-box-pointers">Box Pointers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-rc-and-arc-pointers">Rc and Arc Pointers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-weak-pointers">Weak Pointers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-refcell">RefCell</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary">Summary</a></p>
</li>
</ul>
<h2 id="heading-box-pointers"><code>Box</code> Pointers</h2>
<p><code>Box</code> is the most straightforward type of a smart pointer. It allows you to manually allocate memory in the heap.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[allow(dead_code)]</span>
<span class="hljs-meta">#[derive(Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Point</span></span> {
    x: <span class="hljs-built_in">f32</span>,
    y: <span class="hljs-built_in">f32</span>,
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> point = <span class="hljs-built_in">Box</span>::new(Point { x: <span class="hljs-number">0.0</span>, y: <span class="hljs-number">0.0</span> });
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, point);
}
</code></pre>
<p>You can access the contents of a <code>Box</code> pointer like you would with a regular variable:</p>
<pre><code class="lang-rust"><span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, point.x); <span class="hljs-comment">// -&gt; output: 0.0</span>
<span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, point.y); <span class="hljs-comment">// -&gt; output: 0.0</span>
</code></pre>
<p>It works almost identically to <code>malloc</code> in C and <code>new</code> in c++, with the exception that <code>Box</code> automatically gets freed when it goes out of scope, or when the program execution ends, as opposed to manually freeing the allocation in <code>malloc</code> and <code>new</code>.</p>
<h2 id="heading-rc-and-arc-pointers"><code>Rc</code> and <code>Arc</code> Pointers</h2>
<p>I’m putting <code>Rc</code> and <code>Arc</code> together because they’re very similar in what they do and how they work.</p>
<p><code>Rc</code> and <code>Arc</code> are reference counted pointers that allow multiple ownership of a memory allocation. Similar to <code>Box</code>, they allocate memory in the heap, but what differentiates them from <code>Box</code> is that they also include a reference count.</p>
<p><code>Rc</code> and <code>Arc</code> allows you to create multiple clones of a reference to a memory allocation. This allows you to move those references to multiple scopes, and in the case of <code>Arc</code>, multiple threads, without borrowing. For example:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::sync::Arc;
<span class="hljs-keyword">use</span> std::thread;
<span class="hljs-keyword">use</span> std::thread::JoinHandle;

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

<span class="hljs-keyword">impl</span> GameState {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>() -&gt; <span class="hljs-keyword">Self</span> {
        GameState { user_name: <span class="hljs-string">"Chigozie"</span>.to_string() }
    }
}

<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> threads: <span class="hljs-built_in">Vec</span>&lt;JoinHandle&lt;()&gt;&gt; = <span class="hljs-built_in">vec!</span>[];
    <span class="hljs-keyword">let</span> game_state = Arc::new( GameState::new() );

    <span class="hljs-keyword">let</span> g1 = Arc::clone(&amp;game_state); <span class="hljs-comment">// first clone</span>
    threads.push(thread::spawn(<span class="hljs-keyword">move</span> || {
        <span class="hljs-keyword">let</span> username = &amp;g1.user_name;
        <span class="hljs-comment">// ...</span>
    }));

    <span class="hljs-keyword">let</span> g2 = Arc::clone(&amp;game_state); <span class="hljs-comment">// second clone</span>
    threads.push(thread::spawn(<span class="hljs-keyword">move</span> || {
        <span class="hljs-keyword">let</span> username = &amp;g2.user_name;
        <span class="hljs-comment">// ...</span>
    }));

    <span class="hljs-keyword">let</span> g3 = Arc::clone(&amp;game_state); <span class="hljs-comment">// third clone</span>
    threads.push(thread::spawn(<span class="hljs-keyword">move</span> || {
        <span class="hljs-keyword">let</span> username = &amp;g3.user_name;
        <span class="hljs-comment">// ...</span>
    }));

    <span class="hljs-keyword">let</span> g4 = Arc::clone(&amp;game_state); <span class="hljs-comment">// fourth clone</span>
    threads.push(thread::spawn(<span class="hljs-keyword">move</span> || {
        <span class="hljs-keyword">let</span> username = &amp;g4.user_name;
        <span class="hljs-comment">// ...</span>
    }));

    <span class="hljs-keyword">let</span> g5 = Arc::clone(&amp;game_state); <span class="hljs-comment">// fifth clone</span>
    threads.push(thread::spawn(<span class="hljs-keyword">move</span> || {
        <span class="hljs-keyword">let</span> username = &amp;g5.user_name;
        <span class="hljs-comment">// ...</span>
    }));

    <span class="hljs-keyword">for</span> th <span class="hljs-keyword">in</span> threads {
        th.join().unwrap();
    }
}
</code></pre>
<p>In this example, I created an instance of a game struct in an <code>Arc</code> data structure, spawned five threads, then created and passed five more <code>Arc</code> references of the game struct to the five spawned threads.</p>
<p>The difference between <code>Rc</code> and <code>Arc</code> pointers is that references in <code>Arc</code> pointers are counted atomically, while references in <code>Rc</code> pointers are counted using the usual mathematical operations. This means that the operations that go into counting the references in <code>Arc</code> pointers are guaranteed to not be interrupted or overlapped by other threads or processes, making them very useful for multi-threaded environments.</p>
<p>One useful application of <code>Rc</code> and <code>Arc</code> pointers is in reference-based data structures, like linked lists, where each node has its value and a reference to the next node. For example:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::rc::Rc;

<span class="hljs-meta">#[derive(Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Node</span></span> {
    value: <span class="hljs-built_in">i32</span>,
    next: <span class="hljs-built_in">Option</span>&lt;Rc&lt;Node&gt;&gt;,
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-comment">// A chain of nodes</span>
    <span class="hljs-keyword">let</span> node1 = Rc::new(Node { value: <span class="hljs-number">1</span>, next: <span class="hljs-literal">None</span> });
    <span class="hljs-keyword">let</span> node2 = Rc::new(Node { value: <span class="hljs-number">2</span>, next: <span class="hljs-literal">Some</span>(Rc::clone(&amp;node1)) });
    <span class="hljs-keyword">let</span> node3 = Rc::new(Node { value: <span class="hljs-number">3</span>, next: <span class="hljs-literal">Some</span>(Rc::clone(&amp;node2)) });

    <span class="hljs-comment">// Multiple owners of node2</span>
    <span class="hljs-keyword">let</span> another_ref_to_node2 = Rc::clone(&amp;node2);

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Node 3: {:?}"</span>, node3);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Another reference to Node 2: {:?}"</span>, another_ref_to_node2);
}
</code></pre>
<p>The memory allocations pointed to by <code>Rc</code> and <code>Arc</code> references are dropped when their reference counts goes to 0. The reference count of <code>Rc</code> and <code>Arc</code> pointers goes to 0 when it and all its clones have gone out of scope, or have been dropped manually.</p>
<h2 id="heading-weak-pointers"><code>Weak</code> Pointers</h2>
<p>Unlike <code>Arc</code> or <code>Rc</code> pointers, <code>Weak</code> pointers are non-owning references to memory allocations. This means that they don’t count towards ownership of the memory allocation and don’t stop memory allocations from being dropped.</p>
<p><code>Weak</code> references are helpful in scenarios where you might prefer a reference to a memory allocation to prevent it from being deallocated. A good example of a scenario like this is a doubly linked list, where each node holds a reference to the next node and the previous node:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1729610464614/f2f11dcd-56e9-401d-b35b-f5a29d8d9dc5.png" alt="Diagram of a doubly linked list. Each node in the doubly linked list has a pointer to the node that comes before it and the node that comes after it." class="image--center mx-auto" width="4095" height="1290" loading="lazy"></p>
<p>A scenario like this using <code>Rc</code> or <code>Arc</code> for both the next and previous nodes can cause reference cycles. Reference cycles prevent nodes from being deallocated because for one node to be deallocated all <code>Arc</code> or <code>Rc</code> references to it must be 0. Since the nodes in this case hold references to other nodes that also hold references back to it, both nodes can’t be deallocated automatically and they can end up stopping all other nodes in the data structure from being deallocated, causing a memory leak.</p>
<p>To prevent reference cycles while allowing nodes to both reference previous and next nodes, you can make each node’s reference to its previous node a <code>Weak</code> reference. For example:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::rc::{Rc, Weak};
<span class="hljs-keyword">use</span> std::cell::RefCell;

<span class="hljs-meta">#[derive(Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Node</span></span> {
    value: <span class="hljs-built_in">i32</span>,
    next: <span class="hljs-built_in">Option</span>&lt;Rc&lt;RefCell&lt;Node&gt;&gt;&gt;,
    prev: <span class="hljs-built_in">Option</span>&lt;Weak&lt;RefCell&lt;Node&gt;&gt;&gt;, <span class="hljs-comment">// Weak reference to avoid cycles</span>
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> node1 = Rc::new(RefCell::new(Node { value: <span class="hljs-number">1</span>, next: <span class="hljs-literal">None</span>, prev: <span class="hljs-literal">None</span> }));
    <span class="hljs-keyword">let</span> node2 = Rc::new(RefCell::new(Node { value: <span class="hljs-number">2</span>, next: <span class="hljs-literal">None</span>, prev: <span class="hljs-literal">Some</span>(Rc::downgrade(&amp;node1)) }));

    <span class="hljs-comment">// Set node1's next to node2</span>
    node1.borrow_mut().next = <span class="hljs-literal">Some</span>(Rc::clone(&amp;node2));

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Node 1: {:?}"</span>, node1);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Node 2: {:?}"</span>, node2);
}
</code></pre>
<p>However, since <code>Weak</code> references have non-owning references to memory allocations, they need to be upgraded to <code>Rc</code> or <code>Arc</code> references with <code>.upgrade()</code> to allow access to the memory allocation they point to.</p>
<p>Also, as you can see in code example below (as well as above on line 13), <code>Rc</code> and <code>Arc</code> references can be downgraded to <code>Weak</code> references with <code>Rc::downgrade()</code> or <code>Arc::downgrade()</code>:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::rc::{Rc, Weak};

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> strong = Rc::new(<span class="hljs-number">5</span>);
    <span class="hljs-keyword">let</span> weak = Rc::downgrade(&amp;strong);

    <span class="hljs-comment">// Drop the weak reference</span>
    <span class="hljs-built_in">drop</span>(weak);

    <span class="hljs-comment">// try to upgrade the weak reference</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Some</span>(shared) = weak.upgrade() {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Data is still alive: {}"</span>, shared);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Data has been dropped"</span>);
    }
}
</code></pre>
<p>Running this results in the following output:</p>
<pre><code class="lang-rust">Data has been dropped
</code></pre>
<p>This shows that only having weak references to a memory allocation doesn’t prevent it from being dropped. If a <code>Weak</code> pointer’s memory allocation is dropped, calling <code>.upgrade()</code> on the <code>Weak</code> pointer would return <code>None</code>.</p>
<h2 id="heading-refcell"><code>RefCell</code></h2>
<p>To ensure memory safety, Rust doesn’t allow you to mutate the data that smart pointers point to. This can prevent hidden mutations, but can become really inconvenient when you need to build something that is dynamically changing (for example the ability to add a new node to anywhere in a linked-list data structure).</p>
<p><code>RefCell</code> allows you to overcome this limitation because it is a data structure that allows interior mutability of immutable variables by enforcing Rust’s borrowing rules at runtime.</p>
<p>You may have noticed it’s usage in the <code>Weak</code> pointer example earlier:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::rc::{Rc, Weak};
<span class="hljs-keyword">use</span> std::cell::RefCell;

<span class="hljs-meta">#[derive(Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Node</span></span> {
    value: <span class="hljs-built_in">i32</span>,
    next: <span class="hljs-built_in">Option</span>&lt;Rc&lt;RefCell&lt;Node&gt;&gt;&gt;,
    prev: <span class="hljs-built_in">Option</span>&lt;Weak&lt;RefCell&lt;Node&gt;&gt;&gt;,
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> node1 = Rc::new(RefCell::new(Node { value: <span class="hljs-number">1</span>, next: <span class="hljs-literal">None</span>, prev: <span class="hljs-literal">None</span> }));
    <span class="hljs-keyword">let</span> node2 = Rc::new(RefCell::new(Node { value: <span class="hljs-number">2</span>, next: <span class="hljs-literal">None</span>, prev: <span class="hljs-literal">Some</span>(Rc::downgrade(&amp;node1)) }));

    <span class="hljs-comment">// Set node1's next to node2</span>
    node1.borrow_mut().next = <span class="hljs-literal">Some</span>(Rc::clone(&amp;node2));

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Node 1: {:?}"</span>, node1);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Node 2: {:?}"</span>, node2);
}
</code></pre>
<p>You can call <code>.borrow()</code> and <code>.borrow_mut()</code> on a <code>RefCell</code> type to borrow references to its internal value at runtime, while keeping its own type as immutable making it useful in cases like this that require immutability.</p>
<p>Mutable and immutable borrows in a <code>RefCell</code> type work just like regular borrows that are checked at compile time, but they allow you to bypass compile time restrictions to be checked instead at runtime.</p>
<p>One major borrowing rule to look out for is the “single mutable ownership and multiple immutable ownership” rule. Borrowing two mutable references to a <code>RefCell</code> would result in a panic, crashing the application. For example:</p>
<pre><code class="lang-rust"><span class="hljs-meta">#![allow(unused_variables)]</span>
<span class="hljs-meta">#![allow(dead_code)]</span>
<span class="hljs-meta">#![allow(unused_mut)]</span>
<span class="hljs-keyword">use</span> std::cell::RefCell;

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> counter = RefCell::new(<span class="hljs-number">100</span>);
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> c1 = counter.borrow_mut();
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> c2 = counter.borrow_mut();

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"I'm done"</span>);
}

<span class="hljs-comment">/**
 * output:
 *  thread 'main' panicked at src/main.rs:9:26:
 *  already borrowed: BorrowMutError
 *  note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
 */</span>
</code></pre>
<h2 id="heading-summary">Summary</h2>
<p>To give an overview of the points made in this article, there are four common types of smart pointers in Rust:</p>
<ul>
<li><p><code>Box</code> is used for manually allocating memory in the heap (similar to <code>malloc</code> and <code>new</code> in C and C++ respectively)</p>
</li>
<li><p><code>Rc</code> and <code>Arc</code> are used for allowing multiple ownership of a memory allocation. <code>Arc</code> is best for multi-threaded environments, and <code>Rc</code> is best for single-threaded environments.</p>
</li>
<li><p><code>Weak</code> is best used in giving multiple ownership of a memory allocation while preventing reference cycles.</p>
</li>
<li><p><code>RefCell</code> allows mutability in scenarios that require immutability, for example, in smart pointers.</p>
</li>
</ul>
<p>I hope this article has provided clarity on smart pointers in Rust and how they work. Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What are Lifetimes in Rust? Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Lifetimes are fundamental mechanisms in Rust. There's a very high chance you'll need to work with lifetimes in any Rust project that has any sort of complexity. Even though they are important to Rust projects, lifetimes can be quite tricky to wrap yo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-are-lifetimes-in-rust-explained-with-code-examples/</link>
                <guid isPermaLink="false">66db602d7e903d0d43f602aa</guid>
                
                    <category>
                        <![CDATA[ Rust ]]>
                    </category>
                
                    <category>
                        <![CDATA[ rust lang ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oduah Chigozie ]]>
                </dc:creator>
                <pubDate>Fri, 06 Sep 2024 20:03:57 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1725652969333/ba8a3fb6-3ac8-40e0-91e6-3e32e7f7b4b4.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Lifetimes are fundamental mechanisms in Rust. There's a very high chance you'll need to work with lifetimes in any Rust project that has any sort of complexity.</p>
<p>Even though they are important to Rust projects, lifetimes can be quite tricky to wrap your head around. So I created this guide to provide more clarity on what they are and when you should use them.</p>
<h3 id="heading-prerequisites-for-this-tutorial">Prerequisites for this Tutorial</h3>
<p>To get the most out of this tutorial, you'll need the following:</p>
<ul>
<li><p>At least beginner-level familiarity with Rust: This tutorial doesn't help with learning how to code in Rust. It only helps with understanding lifetimes in Rust and how they work</p>
</li>
<li><p>Familiarity with generics: Generics in Rust work identically to how they do in popular programming languages. Knowledge of how generics work in any language would be helpful.</p>
</li>
<li><p>Knowing how the borrow checker works isn't as much a requirement as the last two above, but it would be helpful. Knowledge of how lifetimes work also helps in understanding how the borrow checker works.</p>
</li>
</ul>
<h2 id="heading-so-what-are-lifetimes-in-rust">So, What are Lifetimes in Rust?</h2>
<p>For Rust's <a target="_blank" href="https://doc.rust-lang.org/rust-by-example/scope/borrow.html">borrow checker</a> to ensure safety throughout your code, it needs to know how long all the data in the program will live during its execution. This becomes difficult to do in certain situations, and those situations are where you need to use explicit lifetime annotations.</p>
<p>Lifetimes in Rust are mechanisms for ensuring that all borrows that occur within your code are valid. A variable's lifetime is how long it lives within the program's execution, starting from when it's initialized and ending when it's destroyed in the program.</p>
<p>The borrow checker can detect the lifetimes of variables in many cases. But in cases where it can't, you have to assist it with explicit lifetime annotations.</p>
<p>The syntax for explicit lifetime annotations is a single quote followed by a set of characters for identification (for example, <code>'static</code>, <code>'a</code>) as in:</p>
<pre><code class="lang-rust">max&lt;<span class="hljs-symbol">'a</span>&gt;
</code></pre>
<p>The lifetime annotation indicates that <code>max</code> should live at most as long as <code>'a</code>.</p>
<p>Using multiple lifetimes follows the same syntax:</p>
<pre><code class="lang-rust">max&lt;<span class="hljs-symbol">'a</span>, <span class="hljs-symbol">'b</span>&gt;
</code></pre>
<p>In this case, the lifetime annotations indicate that <code>max</code> should live at most as long as <code>'a</code> and <code>'b</code>.</p>
<p>Explicit lifetime annotations are handled similarly to how generics are. Let's take a look at an example:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">max</span></span>&lt;<span class="hljs-symbol">'a</span>&gt;(s1: &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">str</span>, s2: &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-comment">// return the longest string out of the two</span>
}
</code></pre>
<p>In the example, the lifetime annotations indicate that <code>max</code> should live at most as long as the lifetimes of <code>s1</code> or <code>s2</code>. It also indicates that <code>max</code> returns a reference that lives as long as <code>s1</code>.</p>
<p>A Rust project has many cases that would require explicit lifetime annotations, and in the next few sections, we'll go over each of them.</p>
<h2 id="heading-lifetime-annotations-in-functions">Lifetime Annotations in Functions</h2>
<p>A function only needs an explicit lifetime annotation when it returns a reference from any of its arguments. Let's take an example:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">max</span></span>&lt;<span class="hljs-symbol">'a</span>&gt;(s1: &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">str</span>, s2: &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> s1.len() &gt; s2.len() {
        s1
    } <span class="hljs-keyword">else</span> {
        s2
    }
}
</code></pre>
<p>If you remove the lifetime annotations, you'll get an LSP (Language Server Protocol) warning to include the lifetime annotations. If you ignore LSP's warning message and compile the code, you'll get the same message as a compiler error. For example:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">max</span></span>(s1: &amp;<span class="hljs-built_in">str</span>, s2: &amp;<span class="hljs-built_in">str</span>) -&gt; &amp;<span class="hljs-built_in">str</span> {
    <span class="hljs-keyword">if</span> s1.len() &gt; s2.len() {
        s1
    } <span class="hljs-keyword">else</span> {
        s2
    }
}

<span class="hljs-comment">/**
 * Output -&gt;
 *
error[E0106]: missing lifetime specifier
  --&gt; src/main.rs:44:31
   |
44 | fn max(s1: &amp;str, s2: &amp;str) -&gt; &amp;str {
   |            ----      ----     ^ expected named lifetime parameter
   |
   = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `s1` or `s2`
help: consider introducing a named lifetime parameter
   |
44 | fn max&lt;'a&gt;(s1: &amp;'a str, s2: &amp;'a str) -&gt; &amp;'a str {
   |       ++++      ++           ++          ++

For more information about this error, try `rustc --explain E0106`.
error: could not compile `lifetime-test` (bin "lifetime-test") due to 1 previous error
 ***********************
 */</span>
</code></pre>
<p>On the other hand, a function doesn't need explicit lifetimes if it isn't returning a reference in its arguments. For example:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">print_longest</span></span>(s1: &amp;<span class="hljs-built_in">str</span>, s2: &amp;<span class="hljs-built_in">str</span>) {
    <span class="hljs-keyword">if</span> s1.len() &gt; s2.len() {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{s1} is longer than {s2}"</span>)
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{s2} is longer than {s1}"</span>)
    }
}
</code></pre>
<p>A function returning a different value doesn't need explicit lifetime annotations either:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">join_strs</span></span>(s1: &amp;<span class="hljs-built_in">str</span>, s2: &amp;<span class="hljs-built_in">str</span>) -&gt; <span class="hljs-built_in">String</span> {
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> joint_string = <span class="hljs-built_in">String</span>::from(s1);
    joint_string.push_str(s2);
    <span class="hljs-keyword">return</span> joint_string;
}
</code></pre>
<p>You only need to specify lifetimes if a function returns a reference from one of its arguments that is a borrowed reference.</p>
<h2 id="heading-lifetime-annotations-in-structs">Lifetime Annotations in Structs</h2>
<p>Structs require explicit lifetime annotations when any of their fields are references. This allows the borrow checker to ensure that the references in the struct's fields live longer than the struct. For example:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Strs</span></span>&lt;<span class="hljs-symbol">'a</span>, <span class="hljs-symbol">'b</span>&gt; {
    x: &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">str</span>,
    y: &amp;<span class="hljs-symbol">'b</span> <span class="hljs-built_in">str</span>,
}
</code></pre>
<p>Without the lifetime annotations, you'll get a similar LSP and compiler error message to the one in the previous section:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">OtherStruct</span></span> {
    x: &amp;<span class="hljs-built_in">str</span>,
    y: &amp;<span class="hljs-built_in">str</span>,
}

<span class="hljs-comment">/**
* Output -&gt;
**********************
error[E0106]: missing lifetime specifier
 --&gt; src/main.rs:7:8
  |
7 |     x: &amp;str,
  |        ^ expected named lifetime parameter
  |
help: consider introducing a named lifetime parameter
  |
6 ~ struct OtherStruct&lt;'a&gt; {
7 ~     x: &amp;'a str,
  |

error[E0106]: missing lifetime specifier
 --&gt; src/main.rs:8:8
  |
8 |     y: &amp;str,
  |        ^ expected named lifetime parameter
  |
help: consider introducing a named lifetime parameter
  |
6 ~ struct OtherStruct&lt;'a&gt; {
7 |     x: &amp;str,
8 ~     y: &amp;'a str,
  |

For more information about this error, try `rustc --explain E0106`.
error: could not compile `lifetime-test` (bin "lifetime-test") due to 2 previous errors
**********************
*/</span>
</code></pre>
<h2 id="heading-lifetime-annotations-in-methods">Lifetime Annotations in Methods</h2>
<p>Lifetime annotations concerning methods can be done as annotations to standalone methods, <code>impl</code> blocks, or traits. Let's look at each of them:</p>
<h3 id="heading-standalone-methods">Standalone Methods:</h3>
<p>Annotating lifetimes on standalone methods is identical to annotating lifetimes in functions:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> Struct {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">max</span></span>&lt;<span class="hljs-symbol">'a</span>&gt;(<span class="hljs-keyword">self</span>: &amp;<span class="hljs-keyword">Self</span>, s1: &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">str</span>, s2: &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> s1.len() &gt; s2.len() {
            s1
        } <span class="hljs-keyword">else</span> {
            s2
        }
    }
}
</code></pre>
<h3 id="heading-impl-blocks"><code>impl</code> Blocks</h3>
<p>Writing explicit lifetime annotations for <code>impl</code> blocks is required if the struct it is associated with has lifetime annotations in its definition. This is the syntax for writing <code>impl</code> blocks with explicit lifetime annotations:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Struct</span></span>&lt;<span class="hljs-symbol">'a</span>&gt; {
}

<span class="hljs-keyword">impl</span>&lt;<span class="hljs-symbol">'a</span>&gt; Struct&lt;<span class="hljs-symbol">'a</span>&gt; {
}
</code></pre>
<p>This allows any method you write in the <code>impl</code> block to return a reference from <code>Struct</code>. For example:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Strs</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>,
}

<span class="hljs-keyword">impl</span>&lt;<span class="hljs-symbol">'a</span>&gt; Strs&lt;<span class="hljs-symbol">'a</span>&gt; {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">max</span></span>(<span class="hljs-keyword">self</span>: &amp;<span class="hljs-keyword">Self</span>) -&gt; &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">str</span> {
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">self</span>.y.len() &gt; <span class="hljs-keyword">self</span>.x.len() {
            <span class="hljs-keyword">self</span>.y
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">self</span>.x
        }
    }
}
</code></pre>
<h3 id="heading-traits">Traits</h3>
<p>Lifetime annotations in traits are dependent on the methods that the trait defines.</p>
<p>Let's look at one example. A method inside a trait definition can use explicit lifetime annotations as a standalone method, and the trait definition won't require explicit lifetime annotations. Like so:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Max</span></span> {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">longest_str</span></span>&lt;<span class="hljs-symbol">'a</span>&gt;(s1: &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">str</span>, s2: &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">impl</span>&lt;<span class="hljs-symbol">'a</span>&gt; Max <span class="hljs-keyword">for</span> Struct&lt;<span class="hljs-symbol">'a</span>&gt; {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">longest_str</span></span>(s1: &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">str</span>, s2: &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">str</span>) {
        <span class="hljs-keyword">if</span> s1.len() &gt; s2.len() {
            s1
        } <span class="hljs-keyword">else</span> {
            s2
        }
    }
}
</code></pre>
<p>If a trait method requires references from the struct its associated with, the trait's definition would require explicit lifetime annotations. For example:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Max</span></span>&lt;<span class="hljs-symbol">'a</span>&gt; {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">max</span></span>(<span class="hljs-keyword">self</span>: &amp;<span class="hljs-keyword">Self</span>) -&gt; &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">str</span>;
}
</code></pre>
<p>Which can be implemented this way:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Strs</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>,
}

<span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Max</span></span>&lt;<span class="hljs-symbol">'a</span>&gt; {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">max</span></span>(<span class="hljs-keyword">self</span>: &amp;<span class="hljs-keyword">Self</span>) -&gt; &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">str</span>;
}

<span class="hljs-keyword">impl</span>&lt;<span class="hljs-symbol">'a</span>&gt; Max&lt;<span class="hljs-symbol">'a</span>&gt; <span class="hljs-keyword">for</span> Strs&lt;<span class="hljs-symbol">'a</span>&gt; {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">max</span></span>(<span class="hljs-keyword">self</span>: &amp;<span class="hljs-keyword">Self</span>) -&gt; &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">str</span> {
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">self</span>.y.len() &gt; <span class="hljs-keyword">self</span>.x.len() {
            <span class="hljs-keyword">self</span>.y
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">self</span>.x
        }
    }
}
</code></pre>
<h2 id="heading-lifetime-annotations-in-enums">Lifetime Annotations in Enums</h2>
<p>Similar to structs, enums need explicit lifetime annotations if any of their fields are references. For example:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Either</span></span>&lt;<span class="hljs-symbol">'a</span>&gt; {
    Str(<span class="hljs-built_in">String</span>),
    Ref(&amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">String</span>),
}
</code></pre>
<h2 id="heading-the-static-lifetime">The <code>'static</code> Lifetime</h2>
<p>In many Rust projects, you'll likely have encountered variables that are <code>'static</code> in lifetimes. In this section, we'll go over a brief overview of what a <code>'static</code> lifetime is, how it works, and where it is commonly used.</p>
<p><code>'static</code> is a reserved lifetime name in Rust. It signifies that the data that a reference points to lives from where it is initialized to the end of the program. This differs slightly from static variables, which are stored directly in the program's binary file. However, all static variables have a <code>'static</code> lifetime.</p>
<p>Variables with <code>'static</code> lifetimes can be created at runtime. But they can't be dropped, only coerced into shorter lifetimes. For example:</p>
<pre><code class="lang-rust"><span class="hljs-comment">// The lifetime annotation 'a is the shorter lifetime of the</span>
<span class="hljs-comment">// two arguments s1 and s2</span>
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">max</span></span>&lt;<span class="hljs-symbol">'a</span>&gt;(s1: &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">str</span>, s2: &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> s1.len() &gt; s2.len() {
        s1
    } <span class="hljs-keyword">else</span> {
        s2
    }
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> first = <span class="hljs-string">"First string"</span>; <span class="hljs-comment">// Longer lifetime</span>

    {
        <span class="hljs-keyword">let</span> second = <span class="hljs-string">"Second string"</span>; <span class="hljs-comment">// Shorter lifetime</span>

        <span class="hljs-comment">// In the max function, the lifetime of first is</span>
        <span class="hljs-comment">// coerced into the lifetime of second</span>
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"The biggest of {} and {} is {}"</span>, first, second, max(first, second));
    };
}
</code></pre>
<p>String literals are examples of values with <code>'static</code> lifetimes. They are also stored in the program's binary file and can be created at runtime.</p>
<p>Rust allows you to declare static variables with the <code>static</code> keyword, using this syntax:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">static</span> IDENTIFIER: &amp;<span class="hljs-symbol">'static</span> <span class="hljs-built_in">str</span> = <span class="hljs-string">"value"</span>;
</code></pre>
<p>Static variables can be declared in any scope, including the global scope. This means that you can use static variables as global variables. For example:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">static</span> FIRST_NAME: &amp;<span class="hljs-symbol">'static</span> <span class="hljs-built_in">str</span> = <span class="hljs-string">"John"</span>;
<span class="hljs-keyword">static</span> LAST_NAME: &amp;<span class="hljs-symbol">'static</span> <span class="hljs-built_in">str</span> = <span class="hljs-string">"Doe"</span>;

<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">"First name: {}"</span>, FIRST_NAME);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Last name: {}"</span>, LAST_NAME);
}
</code></pre>
<p>Static variables can also be mutable or immutable. But working with mutable static variables is only allowed in <code>unsafe</code> blocks because they're unsafe.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">static</span> <span class="hljs-keyword">mut</span> FIRST_NAME: &amp;<span class="hljs-symbol">'static</span> <span class="hljs-built_in">str</span> = <span class="hljs-string">"John"</span>;
<span class="hljs-keyword">static</span> LAST_NAME: &amp;<span class="hljs-symbol">'static</span> <span class="hljs-built_in">str</span> = <span class="hljs-string">"Doe"</span>;

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">unsafe</span> {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"First name: {}"</span>, FIRST_NAME);
    }
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Last name: {}"</span>, LAST_NAME);
    <span class="hljs-keyword">unsafe</span> {
        FIRST_NAME = <span class="hljs-string">"Jane"</span>;
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"First name changed to: {}"</span>, FIRST_NAME);
    }
}
</code></pre>
<h2 id="heading-summary">Summary</h2>
<p>Lifetimes in Rust help the borrow checker ensure that all borrowed references are valid. The borrow checker can detect the lifetimes of variables in many cases, but in cases where it can't you have to assist it with explicit lifetime annotations.</p>
<p>Explicit lifetime annotations are those <code>'a</code>, <code>'b</code>, and <code>'static</code> things you see in many Rust projects. You only need to use them in structures (structs, enums, traits, and impls) that deal with references, and in functions or methods that receive and return references.</p>
<p>In this guide, you learned about explicit lifetime annotations and saw some examples of how to use them. I it gave you some clarity on the topic, and helped you understand lifetimes better.</p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Asynchronous Programming Works in Rust – Futures and Async/Await Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ If you're familiar with languages like JavaScript and Python, you may have heard about asynchronous programming. And perhaps you're wondering how it works in Rust. In this article, I'll give you a simple overview of how asynchronous programming works... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-asynchronous-programming-works-in-rust/</link>
                <guid isPermaLink="false">66be1c3ab712ab343b0b9150</guid>
                
                    <category>
                        <![CDATA[ Rust ]]>
                    </category>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oduah Chigozie ]]>
                </dc:creator>
                <pubDate>Thu, 15 Aug 2024 15:18:18 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723746256888/b046d857-161c-41be-96d0-1c05b1e448b8.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're familiar with languages like JavaScript and Python, you may have heard about asynchronous programming. And perhaps you're wondering how it works in Rust.</p>
<p>In this article, I'll give you a simple overview of how asynchronous programming works in Rust. You'll learn about futures as well as <code>async</code>/<code>.await</code>.</p>
<p>This article isn't a beginner's guide to Rust or asynchronous programming, so you'll need to have some experience with programming in Rust and familiarity with asynchronous programming to get the most out of this guide.</p>
<p>With that said, let's begin!</p>
<h2 id="heading-when-should-you-use-asynchronous-programming">When Should You Use Asynchronous Programming?</h2>
<p>Asynchronous tasks work like a more integrated version of threads. You can use them in a lot of the same scenarios where you can use multiple threads. The benefits async programming provides over multiple threads is that multi-threaded applications have a larger overhead to work on multiple tasks compared to asynchronous applications.</p>
<p>But this doesn’t make asynchronous applications better than multithreaded applications. Multi-threaded programs can run multiple computing-intensive tasks simultaneously – and multiple times faster than if you ran all the tasks in a single thread.</p>
<p>With asynchronous coding, trying to run multiple computing-intensive applications simultaneously will be much slower than just running every task on a single thread.</p>
<p>Asynchronous programming is very good for building applications that make many network requests or many IO operations like file reading and writing.</p>
<p>I can’t cover every case when you’ll want to use asynchronous techniques. But I can say that it’s most beneficial for tasks that have a lot of idle time (for example, waiting for a server to respond to a network request).</p>
<p>During the idle time of an asynchronous task, instead of blocking the thread, the event handler works on other tasks in the program until the asynchronous task is ready to make progress.</p>
<h2 id="heading-overview-of-asynchronous-rust-futures">Overview of Asynchronous Rust – Futures</h2>
<p>The basics of asynchronous Rust are Futures. Futures are similar to promises in JavaScript. They are Rust's way of saying "hey, I'm going to give you the result later, but just hold on to this (the future instance) to keep track of if the result is ready."</p>
<p>Futures are traits, with a <code>poll</code> state that is either <code>Poll::Pending</code> to signify that the future is in the process of executing its task, or <code>Poll::Ready</code> to signify that the future is done with its task.</p>
<p>Futures are lazy. They run when you <code>.await</code> them (we'll look into how to <code>.await</code> them in the next section). <code>.await</code>ing a future pauses the execution of an asynchronous thread, and begins running its task. At this point the result of the <code>poll</code> method is <code>Poll::Pending</code>. When the future is done with its task, <code>poll</code>'s state will become <code>Poll::Ready</code>, and the future will allow it's thread to proceed.</p>
<p>If you want to get more into the technical details about Futures, you can check out <a target="_blank" href="https://rust-lang.github.io/async-book/02_execution/01_chapter.html">the documentation</a>.</p>
<h2 id="heading-asyncawait-in-rust">async/.await in Rust</h2>
<p><code>async</code> and <code>.await</code> are the primary ways you'll be working with asynchronous code in Rust. <code>async</code> is a keyword for declaring asynchronous functions. Within those functions, the <code>.await</code> keyword pauses its execution until the result of the future is ready.</p>
<p>Let's take a look at an example:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">add</span></span>(a: <span class="hljs-built_in">u8</span>, b: <span class="hljs-built_in">u8</span>) -&gt; <span class="hljs-built_in">u8</span> {
    a + b
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">secondFunc</span></span>() -&gt; <span class="hljs-built_in">u8</span> {
    <span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>;
    <span class="hljs-keyword">let</span> b = <span class="hljs-number">20</span>;
    <span class="hljs-keyword">let</span> result = add(a, b).<span class="hljs-keyword">await</span>;
    <span class="hljs-keyword">return</span> result;
}
</code></pre>
<p>Any asynchronous function declared with <code>async fn</code> wraps its return value in a future. On the third line of <code>secondFunc</code>, we <code>.await</code> the future from <code>add(a, b)</code> to get its result before proceeding to return it.</p>
<h2 id="heading-how-to-work-with-asynchronous-operations-in-main">How to Work with Asynchronous Operations in <code>main</code></h2>
<p>Rust doesn’t allow you to <code>async fn</code> main functions. Running asynchronous operations from a non-asynchronous function may lead to some operations not fully concluding before the main thread is exited.</p>
<p>In this section, we’ll look at two ways solve this issue. The two ways to do this are with <code>futures</code> and <code>tokio</code>. Let's look at both.</p>
<h3 id="heading-tokio"><code>tokio</code></h3>
<p><code>tokio</code> is a platform that provides tools and APIs for performing asynchronous applications. <code>tokio</code> also allows you to easily declare an asynchronous main function, which will help with the issue I described earlier.</p>
<p>To install <code>tokio</code> in your project, add this line to its <code>Cargo.toml</code>:</p>
<pre><code class="lang-ini"><span class="hljs-section">[dependencies]</span>
<span class="hljs-attr">tokio</span> = { version = <span class="hljs-string">"1"</span>, features = [<span class="hljs-string">"full"</span>] }
</code></pre>
<p>After adding the line, you can write your <code>main</code> functions like this:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">add</span></span>(a: <span class="hljs-built_in">u8</span>, b: <span class="hljs-built_in">u8</span>) -&gt; <span class="hljs-built_in">u8</span> {
    a + b
}

<span class="hljs-meta">#[tokio::main]</span>
<span class="hljs-keyword">async</span> <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-number">10</span>;
    <span class="hljs-keyword">let</span> b = <span class="hljs-number">20</span>;
    <span class="hljs-keyword">let</span> result = add(a, b).<span class="hljs-keyword">await</span>;
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{result}"</span>);
}
</code></pre>
<h3 id="heading-the-futures-library">The <code>futures</code> library</h3>
<p><code>futures</code> is a library that provides methods for working with asynchronous Rust. For our use case, <code>futures</code> provides <code>futures::executor::block_on()</code>. This method works similar to <code>.await</code> in asynchronous functions. It blocks the main thread, until the result of future is ready. <code>futures::executor::block_on()</code> also returns the result of the completed future.</p>
<p>To install <code>futures</code> in your project, add this line to its <code>Cargo.toml</code>:</p>
<pre><code class="lang-ini"><span class="hljs-section">[dependencies]</span>
<span class="hljs-attr">futures</span> = <span class="hljs-string">"0.3"</span>
</code></pre>
<p>After installing the library, you can do something like this:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> futures::executor::block_on;

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">add</span></span>(a: <span class="hljs-built_in">u8</span>, b: <span class="hljs-built_in">u8</span>) -&gt; <span class="hljs-built_in">u8</span> {
    a + b
}

<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-number">10</span>;
    <span class="hljs-keyword">let</span> b = <span class="hljs-number">20</span>;
    <span class="hljs-keyword">let</span> result = block_on(add(a, b));
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{result}"</span>); 
}
</code></pre>
<p>First, we import the <code>block_on</code> method on the first line and use the method to block the main thread until the result of the <code>add(a, b)</code> function was ready. We also didn’t have to make the <code>main</code> function asynchronous like we did with <code>tokio</code>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Asynchronous programming allows you to run operations in parallel and with less overhead and complexity compared to traditional multi-threading. In Rust, it allows you to build I/O and network applications more efficiently.</p>
<p>While this article should help you become familiar with the basics asynchronous programming in Rust, it’s still just an overview. There are some cases where you'll need to use other constructs in Rust like Pinning, Arcs, and so on.</p>
<p>If you have any questions or thoughts, feel free to reach out to me. Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Get Started with MongoDB in Rust ]]>
                </title>
                <description>
                    <![CDATA[ MongoDB is a popular NoSQL database that has been gaining increasing popularity in recent years. It offers developers a flexible, scalable, and high-performance database solution, which can be used for a wide range of applications.  For Rust programm... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/mongodb-in-rust/</link>
                <guid isPermaLink="false">66ba21ea5ff1162736060bd0</guid>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MongoDB ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Rust ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oduah Chigozie ]]>
                </dc:creator>
                <pubDate>Mon, 20 Feb 2023 20:41:19 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/pexels-ulucas-dube-cantin-10325707.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>MongoDB is a popular NoSQL database that has been gaining increasing popularity in recent years. It offers developers a flexible, scalable, and high-performance database solution, which can be used for a wide range of applications. </p>
<p>For Rust programmers, MongoDB provides an excellent option for storing and retrieving data in a fast, efficient, and reliable way.</p>
<p>Rust is a modern, high-performance systems programming language that was designed for speed, safety, and concurrency. It is well suited for building high-performance, low-level software, and is becoming increasingly popular among developers.</p>
<p>In this article, we will explore how Rust programmers can leverage MongoDB to build high-performance, scalable applications. I will explain how to set up a MongoDB database, and show you how to interact with MongoDB from Rust using the official MongoDB Rust driver. </p>
<p>Whether you are new to MongoDB or an experienced Rust programmer looking to leverage this powerful database technology, this article will provide you with the knowledge and skills you need to get started.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along with the article, you only need the following:</p>
<ul>
<li>Knowledge of Rust.</li>
<li>A system to work with.</li>
<li>Rust installed on your system.</li>
</ul>
<h2 id="heading-getting-started">Getting Started</h2>
<p>To get started with MongoDB, you will need to install the MongoDB Community Edition database software. The following steps will guide you through the installation process.</p>
<h3 id="heading-download-mongodb-community-edition">Download MongoDB Community Edition.</h3>
<p>The first step is to download the MongoDB Community Edition package for your operating system. </p>
<p>You can download the package from the official MongoDB website at <a target="_blank" href="https://www.mongodb.com/try/download/community">https://www.mongodb.com/try/download/community</a>.</p>
<h3 id="heading-install-mongodb-community-edition">Install MongoDB Community Edition.</h3>
<p>After downloading the package, run the installer and follow the prompts to install MongoDB Community Edition on your system.</p>
<h3 id="heading-start-the-mongodb-server">Start the MongoDB server.</h3>
<p>Once the installation is complete, start the MongoDB server by running the following command:</p>
<pre><code class="lang-bash">mongod
</code></pre>
<p>This will start the MongoDB server and it will be listening on port 27017 by default.</p>
<h3 id="heading-install-mongodb-compass">Install MongoDB Compass</h3>
<p>MongoDB Compass is a graphical user interface (GUI) for working with MongoDB. It provides a simple and intuitive way to interact with MongoDB databases, collections, and documents. </p>
<p>To install MongoDB Compass, follow these steps:</p>
<ol>
<li>Go to the official MongoDB website at <a target="_blank" href="https://www.mongodb.com/products/compass">https://www.mongodb.com/products/compass</a> and download the appropriate version for your operating system.</li>
<li>Run the installer and follow the prompts to install MongoDB Compass on your system.</li>
<li>Once the installation is complete, launch MongoDB Compass and connect to your MongoDB server by entering the connection string in the connection dialog.</li>
</ol>
<p>Congratulations, you have now installed the MongoDB Community Edition and MongoDB Compass. You can now start working with MongoDB databases, collections, and documents. </p>
<p>In the next section, we will cover how to set up a project so that you can interact with the database from Rust.</p>
<h2 id="heading-how-to-set-up-your-project">How to Set Up Your Project</h2>
<p>Now that you have MongoDB installed on your system, it's time to set up your Rust project to use the official MongoDB Rust driver. Follow these steps to get started:</p>
<h3 id="heading-create-a-new-rust-project">Create a new Rust project.</h3>
<p>Open your terminal and create a new Rust project by running the following command:</p>
<pre><code class="lang-bash">cargo new myproject
</code></pre>
<p>This will create a new Rust project with the name "myproject".</p>
<h3 id="heading-add-the-mongodb-rust-driver-dependency">Add the MongoDB Rust driver dependency.</h3>
<p>Open the <em>Cargo.toml</em> file in your project directory and add the following dependency to it:</p>
<pre><code class="lang-toml"><span class="hljs-section">[dependencies]</span>
<span class="hljs-attr">mongodb</span> = <span class="hljs-string">"2.3.1"</span>
</code></pre>
<p>This will add the MongoDB Rust driver dependency to your project.</p>
<h3 id="heading-import-the-necessary-libraries">Import the necessary libraries.</h3>
<p>Open the <em>src/main.rs</em> file in your project directory and import the necessary libraries by adding the following lines to the top of the file:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">extern</span> <span class="hljs-keyword">crate</span> mongodb;
<span class="hljs-keyword">use</span> mongodb::bson::doc;
<span class="hljs-keyword">use</span> mongodb::{Client, options::ClientOptions};
</code></pre>
<p>This will import the <code>doc</code> macro, and the <code>Client</code> and <code>ClientOptions</code> types from the MongoDB Rust driver.</p>
<h3 id="heading-connect-to-your-mongodb-server">Connect to your MongoDB server.</h3>
<p>Add the following code to your <code>main</code> function to connect to your MongoDB server:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> client_options = ClientOptions::parse(<span class="hljs-string">"mongodb://localhost:27017"</span>).<span class="hljs-keyword">await</span>.unwrap();
<span class="hljs-keyword">let</span> client = Client::with_options(client_options).unwrap();
</code></pre>
<p>This will create a new <code>ClientOptions</code> object with the connection string to your MongoDB server. Then create a new <code>Client</code> object with the <code>ClientOptions</code> object.</p>
<p>Congratulations, you have now set up your Rust project to use the official MongoDB Rust driver. </p>
<p>In the next sections, we will cover how to create a database using MongoDB compass.</p>
<h2 id="heading-how-to-create-a-database-in-mongodb">How to Create a Database in MongoDB</h2>
<p>Before you can create a collection in MongoDB, you need to have a database to store it in. In this section, I will show you how to create a new database in MongoDB using MongoDB Compass.</p>
<ol>
<li>Open MongoDB Compass and click the <strong>Connect</strong> button in the top left corner of the screen.</li>
<li>In the <strong>New Connection</strong> window, enter the connection details for your MongoDB instance. This includes the hostname, port number, and authentication details if necessary.</li>
<li>Click <strong>Connect</strong> to establish a connection to your MongoDB instance.</li>
<li>In the left-hand navigation pane, click <strong>Databases</strong> to view a list of existing databases.</li>
<li>Click the <strong>Create Database</strong> button in the top left corner of the <strong>Databases</strong> window.</li>
<li>Enter a name for your new database (e.g “mydatabase”) and click <strong>Create</strong>.</li>
</ol>
<p>Congratulations, you have created a new database in MongoDB Compass! You can now begin creating collections and adding documents to your database.</p>
<h2 id="heading-how-to-create-a-collection-in-mongodb">How to Create a Collection in MongoDB</h2>
<p>In MongoDB, a database collection is equivalent to a table in a relational database. A collection is a group of MongoDB documents that share a set of common characteristics. </p>
<p>In this section, I will show you how to create a new collection in MongoDB using Rust.</p>
<h3 id="heading-create-a-new-rust-function">Create a new Rust function.</h3>
<p>Open the <em>src/main.rs</em> file in your project directory and create a new function called <code>create_collection</code>. This function will create a new collection in your MongoDB database. Add the following code to your <em>main.rs</em> file:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">create_collection</span></span>(client: &amp;Client, db_name: &amp;<span class="hljs-built_in">str</span>, coll_name: &amp;<span class="hljs-built_in">str</span>) {
    <span class="hljs-keyword">let</span> db = client.database(db_name);
    db.create_collection(coll_name, <span class="hljs-literal">None</span>).<span class="hljs-keyword">await</span>.unwrap();
}
</code></pre>
<p>This function takes a <code>Client</code> object, a database name, and a collection name as arguments. Then it creates a new collection in the specified database.</p>
<h3 id="heading-call-the-createcollection-function">Call the <code>create_collection</code> function.</h3>
<p>In your main function, add the following code to call the <code>create_collection</code> function and create a new collection in your MongoDB database:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> client_options = ClientOptions::parse(<span class="hljs-string">"mongodb://localhost:27017"</span>).<span class="hljs-keyword">await</span>.unwrap();
<span class="hljs-keyword">let</span> client = Client::with_options(client_options).unwrap();

<span class="hljs-keyword">let</span> db_name = <span class="hljs-string">"mydatabase"</span>;
<span class="hljs-keyword">let</span> coll_name = <span class="hljs-string">"mycollection"</span>;

create_collection(&amp;client, db_name, coll_name).<span class="hljs-keyword">await</span>;
</code></pre>
<p>This code will create a new <code>Client</code> object and call the <code>create_collection</code> function to create a new collection called “mycollection” in the <code>mydatabase</code> database.</p>
<p>Congratulations, you have now created a new collection in your MongoDB database using Rust. </p>
<p>In the next four sections, we will cover how to perform CRUD operations on your data, starting with inserting a document.</p>
<h2 id="heading-how-to-insert-a-document-into-a-collection-in-mongodb">How to Insert a Document into a Collection in MongoDB</h2>
<p>In MongoDB, a row is equivalent to a document in a collection. In this section, I will show you how to insert a new document into a collection in MongoDB using Rust.</p>
<h3 id="heading-create-a-new-rust-function-1">Create a new Rust function.</h3>
<p>Open the <em>src/main.rs</em> file in your project directory and create a new function called <code>insert_document</code>. This function will insert a new document into the specified collection in your MongoDB database. Add the following code to your <em>main.rs</em> file:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">insert_document</span></span>(client: &amp;Client, db_name: &amp;<span class="hljs-built_in">str</span>, coll_name: &amp;<span class="hljs-built_in">str</span>) {
    <span class="hljs-keyword">let</span> db = client.database(db_name);
    <span class="hljs-keyword">let</span> coll = db.collection(coll_name);

    <span class="hljs-keyword">let</span> doc = doc! { <span class="hljs-string">"name"</span>: <span class="hljs-string">"John"</span>, <span class="hljs-string">"age"</span>: <span class="hljs-number">30</span> };

    coll.insert_one(doc, <span class="hljs-literal">None</span>).<span class="hljs-keyword">await</span>.unwrap();
}
</code></pre>
<p>This function takes a <code>Client</code> object, a database name, and a collection name as arguments. It then creates a new <code>Collection</code> object for the specified collection and inserts a new document into it.</p>
<h3 id="heading-call-the-insertdocument-function">Call the <code>insert_document</code> function.</h3>
<p>In your main function, add the following code to call the <code>insert_document</code> function and insert a new document into your MongoDB collection:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> client_options = ClientOptions::parse(<span class="hljs-string">"mongodb://localhost:27017"</span>).<span class="hljs-keyword">await</span>.unwrap();
<span class="hljs-keyword">let</span> client = Client::with_options(client_options).unwrap();

<span class="hljs-keyword">let</span> db_name = <span class="hljs-string">"mydatabase"</span>;
<span class="hljs-keyword">let</span> coll_name = <span class="hljs-string">"mycollection"</span>;

insert_document(&amp;client, db_name, coll_name).<span class="hljs-keyword">await</span>;
</code></pre>
<p>This code will create a new <code>Client</code> object and call its <code>insert_one</code> method to insert a new document with the fields <code>name</code> and <code>age</code> into the collection.</p>
<p>Congratulations, you have now inserted a new document into your MongoDB collection using Rust. </p>
<p>In the next section, I will cover how to retrieve a document from the collection and perform other CRUD operations on your data.</p>
<h2 id="heading-how-to-retrieve-a-document-from-a-collection-in-mongodb">How to Retrieve a Document from a Collection in MongoDB</h2>
<p>In MongoDB, you can retrieve a document from a collection by querying the collection with specific filter criteria. </p>
<p>In this section, I will show you how to retrieve a document from a collection in MongoDB using Rust.</p>
<h3 id="heading-create-a-new-rust-function-2">Create a new Rust function.</h3>
<p>Open the <em>src/main.rs</em> file in your project directory and create a new function called <code>get_document</code>. This function will retrieve a document from the specified collection in your MongoDB database. Add the following code to your <em>main.rs</em> file:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_document</span></span>(client: &amp;Client, db_name: &amp;<span class="hljs-built_in">str</span>, coll_name: &amp;<span class="hljs-built_in">str</span>) {
    <span class="hljs-keyword">let</span> db = client.database(db_name);
    <span class="hljs-keyword">let</span> coll = db.collection(coll_name);

    <span class="hljs-keyword">let</span> filter = doc! {<span class="hljs-string">"name"</span>: <span class="hljs-string">"John"</span>};

    <span class="hljs-keyword">let</span> result = coll.find_one(<span class="hljs-literal">Some</span>(filter), <span class="hljs-literal">None</span>).<span class="hljs-keyword">await</span>.unwrap();
    <span class="hljs-keyword">match</span> result {
        <span class="hljs-literal">Some</span>(doc) =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, doc),
        <span class="hljs-literal">None</span> =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"No document found"</span>),
    }
}
</code></pre>
<p>This function takes a <code>Client</code> object, a database name, and a collection name as arguments. It then creates a new <code>Collection</code> object for the specified collection and retrieves a document from it that matches the specified filter criteria.</p>
<p>In this example, we are retrieving a document in the collection that has a field called “name” with the value “John”.</p>
<h3 id="heading-call-the-getdocument-function">Call the <code>get_document</code> function.</h3>
<p>In your main function, add the following code to call the <code>get_document</code> function and retrieve a document from your MongoDB collection:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> client_options = ClientOptions::parse(<span class="hljs-string">"mongodb://localhost:27017"</span>).<span class="hljs-keyword">await</span>.unwrap();
<span class="hljs-keyword">let</span> client = Client::with_options(client_options).unwrap();

<span class="hljs-keyword">let</span> db_name = <span class="hljs-string">"mydatabase"</span>;
<span class="hljs-keyword">let</span> coll_name = <span class="hljs-string">"mycollection"</span>;

get_document(&amp;client, db_name, coll_name).<span class="hljs-keyword">await</span>;
</code></pre>
<p>This code will create a new <code>Client</code> object, and retrieve a document from the <code>mycollection</code> collection that matches the filter criteria.</p>
<p>Congratulations, you have now retrieved a document from your MongoDB collection using Rust. In the next section, we will cover how to delete data from the collection.</p>
<h2 id="heading-how-to-delete-a-document-from-a-collection-in-mongodb">How to Delete a Document from a Collection in MongoDB</h2>
<p>In MongoDB, you can delete a document from a collection by specifying one or more criteria to match the document. </p>
<p>In this section, I will show you how to delete a document from a collection in MongoDB using Rust.</p>
<h3 id="heading-create-a-new-rust-function-3">Create a new Rust function.</h3>
<p>Open the <em>src/main.rs</em> file in your project directory and create a new function called <code>delete_document</code>. This function will delete a document from the specified collection in your MongoDB database. Add the following code to your <em>main.rs</em> file:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">delete_document</span></span>(client: &amp;Client, db_name: &amp;<span class="hljs-built_in">str</span>, coll_name: &amp;<span class="hljs-built_in">str</span>) {
    <span class="hljs-keyword">let</span> db = client.database(db_name);
    <span class="hljs-keyword">let</span> coll = db.collection(coll_name);

    <span class="hljs-keyword">let</span> filter = doc! {<span class="hljs-string">"name"</span>: <span class="hljs-string">"John"</span>};
    coll.delete_one(filter, <span class="hljs-literal">None</span>).<span class="hljs-keyword">await</span>.unwrap();
}
</code></pre>
<p>This function takes a <code>Client</code> object, a database name, and a collection name as arguments. It then creates a new <code>Collection</code> object for the specified collection and deletes a document from it that matches the specified filter criteria.</p>
<p>In this example, we are deleting a document from the collection that has a field called “name” with the value “John”.</p>
<h3 id="heading-call-the-deletedocument-function">Call the <code>delete_document</code> function.</h3>
<p>In your main function, add the following code to call the <code>delete_document</code> function and delete a document from your MongoDB collection:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> client_options = ClientOptions::parse(<span class="hljs-string">"mongodb://localhost:27017"</span>).<span class="hljs-keyword">await</span>.unwrap();
<span class="hljs-keyword">let</span> client = Client::with_options(client_options).unwrap();

<span class="hljs-keyword">let</span> db_name = <span class="hljs-string">"mydatabase"</span>;
<span class="hljs-keyword">let</span> coll_name = <span class="hljs-string">"mycollection"</span>;

delete_document(&amp;client, db_name, coll_name).<span class="hljs-keyword">await</span>;
</code></pre>
<p>This code will create a new <code>Client</code> object, and delete a document from the <code>mycollection</code> collection that matches the filter criteria.</p>
<p>Congratulations, you have now deleted a document from your MongoDB collection using Rust. </p>
<p>In the next section, I will cover how to modify documents in your collection.</p>
<h2 id="heading-how-to-modify-a-document-in-a-collection-in-mongodb">How to Modify a Document in a Collection in MongoDB</h2>
<p>In MongoDB, you can modify a document in a collection by updating one or more fields in the document. In this section, I will show you how to modify a document in a collection in MongoDB using Rust.</p>
<h3 id="heading-create-a-new-rust-function-4">Create a new Rust function.</h3>
<p>Open the <em>src/main.rs</em> file in your project directory and create a new function called <code>update_document</code>. This function will update a document in the specified collection in your MongoDB database. Add the following code to your main.rs file:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">update_document</span></span>(client: &amp;Client, db_name: &amp;<span class="hljs-built_in">str</span>, coll_name: &amp;<span class="hljs-built_in">str</span>) {
    <span class="hljs-keyword">let</span> db = client.database(db_name);
    <span class="hljs-keyword">let</span> coll = db.collection(coll_name);

    <span class="hljs-keyword">let</span> filter = doc! {<span class="hljs-string">"name"</span>: <span class="hljs-string">"John"</span>};
    <span class="hljs-keyword">let</span> update = doc! {<span class="hljs-string">"$set"</span>: {<span class="hljs-string">"age"</span>: <span class="hljs-number">35</span>}};
    coll.update_one(filter, update, <span class="hljs-literal">None</span>).<span class="hljs-keyword">await</span>.unwrap();
}
</code></pre>
<p>This function takes a <code>Client</code> object, a database name, and a collection name as arguments. It then creates a new <code>Collection</code> object for the specified collection and updates a document in it that matches the specified filter criteria.</p>
<p>In this example, we are updating a document in the collection that has a field called “name” with the value “John”. We are setting the value of the “age” field to “35”.</p>
<h3 id="heading-call-the-updatedocument-function">Call the <code>update_document</code> function.</h3>
<p>In your main function, add the following code to call the <code>update_document</code> function and update a document in your MongoDB collection:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> client_options = ClientOptions::parse(<span class="hljs-string">"mongodb://localhost:27017"</span>).<span class="hljs-keyword">await</span>.unwrap();
<span class="hljs-keyword">let</span> client = Client::with_options(client_options).unwrap();

<span class="hljs-keyword">let</span> db_name = <span class="hljs-string">"mydatabase"</span>;
<span class="hljs-keyword">let</span> coll_name = <span class="hljs-string">"mycollection"</span>;

update_document(&amp;client, db_name, coll_name).<span class="hljs-keyword">await</span>;
</code></pre>
<p>This code will create a new <code>Client</code> object, and update a document in the <code>mycollection</code> collection that matches the filter criteria.</p>
<p>Congratulations, you have now updated a document in your MongoDB collection using Rust. Now, you have performed all basic CRUD operations on a MongoDB database.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, I have introduced you to MongoDB and how to use it with Rust. I have covered the basics of setting up a MongoDB server, creating a database, and creating a collection within the database. I have also shown you how to insert, retrieve, modify, and delete data from your MongoDB database using Rust.</p>
<p>By leveraging the Rust programming language and the MongoDB database, you can build robust and scalable applications that can handle large amounts of data. Rust's performance and safety features make it an excellent choice for working with databases like MongoDB.</p>
<p>I hope that this article has provided you with a solid foundation for working with MongoDB in Rust. With the knowledge gained in this article, you should be able to build a wide range of applications that require a database backend.</p>
<p>Thank you for reading, and happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What Are Solidity Modifiers? Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ In this article, we will explore the various ways you can use modifiers in Solidity to modify the behavior of functions.  We will cover topics such as the syntax for defining and using modifiers, the _; symbol, using multiple modifiers on a single fu... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-are-solidity-modifiers/</link>
                <guid isPermaLink="false">66ba21ede408f68fad73cfbe</guid>
                
                    <category>
                        <![CDATA[ clean code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Smart Contracts ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Solidity ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oduah Chigozie ]]>
                </dc:creator>
                <pubDate>Fri, 06 Jan 2023 18:18:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/shubham-dhage-UxDU0Gg5pqQ-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, we will explore the various ways you can use modifiers in Solidity to modify the behavior of functions. </p>
<p>We will cover topics such as the syntax for defining and using modifiers, the <code>_;</code> symbol, using multiple modifiers on a single function, modifiers with arguments, enum-based modifiers, inherited and overridden modifiers, and examples of how to use modifiers in real-world contracts. </p>
<p>By the end of this article, you will have a deep understanding of how modifiers work and how to use them effectively in your Solidity code.</p>
<h2 id="heading-what-are-solidity-modifiers">What are Solidity Modifiers?</h2>
<p>A modifier is a special type of function that you use to modify the behavior of other functions. Modifiers allow you to add extra conditions or functionality to a function without having to rewrite the entire function.</p>
<p>To define a modifier, you use the <code>modifier</code> keyword followed by the name of the modifier and any parameters it may have. </p>
<p>Here is an example for a modifier:</p>
<pre><code>modifier onlyOwner {
    <span class="hljs-built_in">require</span>(msg.sender == owner);
    _;
}
</code></pre><p>In this example, the <code>onlyOwner</code> modifier has no parameters and includes a <code>require</code> statement that checks that the message sender is the contract owner. </p>
<p>If the message sender is the contract owner, the function will be executed. If the message sender is not the contract owner, the function will not execute.</p>
<p>To use a modifier, attach it to a function by placing it in the function definition. For example:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">changeOwner</span>(<span class="hljs-params">address newOwner</span>) <span class="hljs-title">onlyOwner</span> <span class="hljs-title">public</span> </span>{
    <span class="hljs-comment">// function body</span>
}
</code></pre><p>In this example, the <code>changeOwner</code> function has the <code>onlyOwner</code> modifier attached to it. This means that in order to execute the <code>changeOwner</code> function, the caller must be the contract owner. </p>
<p>If the message sender is not the contract owner, the <code>require</code> statement in the <code>onlyOwner</code> modifier will fail and the function will not execute.</p>
<h2 id="heading-how-does-the-symbol-work">How Does the <code>_;</code> Symbol Work?</h2>
<p>The <code>_;</code> symbol is a special symbol that is used in Solidity modifiers to indicate the end of the modifier and the beginning of the function that the modifier is modifying.</p>
<p>The body of a modifier is made up of one or more statements that are used to modify the behavior of the function, and the <code>_;</code> symbol.</p>
<p>Here is the <code>onlyOwner</code> modifier with the <code>_;</code> symbol:</p>
<pre><code>modifier onlyOwner {
    <span class="hljs-built_in">require</span>(msg.sender == owner);
    _;
}
</code></pre><p>Without the <code>_;</code> symbol, the compiler would not know where to insert the code from the modifier into the function.</p>
<h2 id="heading-how-to-use-multiple-modifiers-on-a-function">How to Use Multiple Modifiers on a Function</h2>
<p>You may want to use multiple modifiers on a single function. Solidity lets you use more than one modifier on a function as in the example below:</p>
<pre><code class="lang-solidity"><span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">MyContract</span></span>{
   <span class="hljs-keyword">address</span> owner;

   <span class="hljs-function"><span class="hljs-keyword">modifier</span> <span class="hljs-title">ownerChanges</span> </span>{
       <span class="hljs-keyword">_</span>;
       <span class="hljs-built_in">require</span>(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span> <span class="hljs-operator">=</span><span class="hljs-operator">=</span> owner);
   }

   <span class="hljs-function"><span class="hljs-keyword">modifier</span> <span class="hljs-title">onlyOwner</span> </span>{
       <span class="hljs-built_in">require</span>(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span> <span class="hljs-operator">=</span><span class="hljs-operator">=</span> owner);
       <span class="hljs-keyword">_</span>;
   }

   <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">changeOwner</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> newOwner</span>) <span class="hljs-title">onlyOwner</span> <span class="hljs-title">ownerChanges</span> <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
       owner <span class="hljs-operator">=</span> newOwner;
   }
}
</code></pre>
<p>The order you place your modifiers in doesn’t matter. When you call the <code>changeOwner</code> function, the virtual machine executes both <code>onlyOwner</code> and <code>ownerChanges</code>.</p>
<h2 id="heading-how-to-use-modifiers-with-arguments">How to Use Modifiers with Arguments</h2>
<p>Modifiers in Solidity can have arguments of any data type supported by Solidity. Modifiers with arguments are defined in the same way as regular modifiers, with the addition of one or more parameters in the function definition.</p>
<p>Here is an example syntax for a modifier with regular arguments:</p>
<pre><code class="lang-solidity"><span class="hljs-function"><span class="hljs-keyword">modifier</span> <span class="hljs-title">onlyAllowedUser</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> user</span>) </span>{
    <span class="hljs-built_in">require</span>(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span> <span class="hljs-operator">=</span><span class="hljs-operator">=</span> user);
    <span class="hljs-keyword">_</span>;
}
</code></pre>
<p>In this example, the <code>onlyAllowedUser</code> modifier has one parameter, <code>user</code>, which is of type <code>address</code>. The modifier includes a <code>require</code> statement that checks the value of the <code>user</code> parameter and only allows the function to execute if the message sender is equal to <code>user</code>.</p>
<p>To use a modifier with regular arguments, you can attach it to a function and pass the appropriate values as arguments. For example:</p>
<pre><code class="lang-solidity"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateData</span>(<span class="hljs-params"><span class="hljs-keyword">uint</span> id, <span class="hljs-keyword">bytes32</span> newData, <span class="hljs-keyword">address</span> user</span>) <span class="hljs-title">onlyAllowedUser</span>(<span class="hljs-params">user</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    <span class="hljs-comment">// function body</span>
}
</code></pre>
<p>In this example, the <code>updateData</code> function has the <code>onlyAllowedUser</code> modifier attached to it and takes an <code>address</code> parameter called <code>user</code>. When the <code>updateData</code> function is called, the value of the <code>user</code> parameter is passed to the <code>onlyAllowedUser</code> modifier.</p>
<h2 id="heading-how-to-create-an-enum-based-modifier">How to Create an Enum-based Modifier</h2>
<p>Another way to use modifiers is to create an enum-based modifier. Enum-based modifiers allow you to specify a set of predefined values that can be used to determine whether or not a function should execute.</p>
<p>To create an enum-based modifier, you first need to define an enum type. An enum type is a special data type that consists of a set of named values called "members". Here is an example enum type:</p>
<pre><code class="lang-solidity"><span class="hljs-keyword">enum</span> <span class="hljs-title">ActionType</span> {
    CREATE,
    UPDATE,
    DELETE
}
</code></pre>
<p>Once you have defined the enum type, you can create an enum-based modifier by adding a parameter of the enum type to your modifier function. </p>
<p>The modifier function should include a required statement that checks the value of the enum parameter and determines whether or not the function should execute. Here is an example of an enum-based modifier:</p>
<pre><code class="lang-solidity"><span class="hljs-function"><span class="hljs-keyword">modifier</span> <span class="hljs-title">onlyAllowedAction</span>(<span class="hljs-params">ActionType action</span>) </span>{
    <span class="hljs-built_in">require</span>(action <span class="hljs-operator">=</span><span class="hljs-operator">=</span> ActionType.CREATE <span class="hljs-operator">|</span><span class="hljs-operator">|</span> action <span class="hljs-operator">=</span><span class="hljs-operator">=</span> ActionType.UPDATE);
    <span class="hljs-keyword">_</span>;
}
</code></pre>
<p>The modifier, called <code>onlyAllowedAction</code>, will only allow the function to which it is attached to execute if the value of the action parameter is either <code>ActionType.CREATE</code> or <code>ActionType.UPDATE</code>. If the value of action is anything else, the <code>require</code> statement will fail and the function will not execute.</p>
<p>To use the enum-based modifier, you would attach it to a function and pass the appropriate enum value as an argument. For example:</p>
<pre><code class="lang-solidity"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateData</span>(<span class="hljs-params"><span class="hljs-keyword">uint</span> id, <span class="hljs-keyword">bytes32</span> newData, ActionType action</span>) <span class="hljs-title">onlyAllowedAction</span>(<span class="hljs-params">action</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    <span class="hljs-comment">// function body</span>
}
</code></pre>
<p>In this example, the <code>updateData</code> function can only be executed if the action parameter is set to either <code>ActionType.CREATE</code> or <code>ActionType.UPDATE</code>.</p>
<h2 id="heading-how-to-inherit-and-override-modifiers">How to Inherit and Override Modifiers</h2>
<p>In Solidity, it is possible to inherit and override modifiers in order to reuse code and customize the behavior of functions.</p>
<p>To inherit a modifier, use the <code>is</code> keyword in the contract that you want to inherit the modifier from. For example:</p>
<pre><code>contract BaseContract {
    modifier onlyOwner {
        <span class="hljs-built_in">require</span>(msg.sender == owner);
        _;
    }
}

contract MyContract is BaseContract {
    <span class="hljs-comment">// functions in MyContract can use the onlyOwner modifier</span>
}
</code></pre><p>In this example, the <code>MyContract</code> contract inherits the <code>onlyOwner</code> modifier from the <code>BaseContract</code>. This means that any function in <code>MyContract</code> can use the <code>onlyOwner</code> modifier. The <code>onlyOwner</code> modifier ensures that only the contract owner can execute the function that it is attached to.</p>
<p>You can also override a modifier by defining a new version of the modifier in a contract that inherits from another contract. To do this, you can use the same name for the modifier and define a new implementation for it. For example:</p>
<pre><code>contract BaseContract {
    modifier onlyOwner {
        <span class="hljs-built_in">require</span>(msg.sender == owner);
        _;
    }
}

contract MyContract is BaseContract {
    <span class="hljs-comment">// override the onlyOwner modifier</span>
    modifier onlyOwner {
        <span class="hljs-built_in">require</span>(msg.sender == newOwner);
        _;
    }
}
</code></pre><p>In this example, the <code>MyContract</code> contract overrides the onlyOwner modifier from the <code>BaseContract</code>. This means that any function in <code>MyContract</code> that uses the <code>onlyOwner</code> modifier will now check that the message sender is equal to the <code>newOwner</code> variable, rather than the <code>owner</code> variable.</p>
<p>Inheriting and overriding modifiers can be a useful way to reuse code and customize the behavior of functions in your Solidity contracts.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Modifiers in Solidity are special functions that modify the behavior of other functions. They allow developers to add extra conditions or functionality without having to rewrite the entire function. </p>
<p>Modifiers can have arguments and can be inherited and overridden to customize their behavior, and they can be used in combination with other modifiers to further customize the behavior of functions.</p>
<p>Enum-based modifiers allow developers to specify a set of predefined values to determine whether or not a function should execute. State-based modifiers use the contract's current state to determine whether or not a function should execute. </p>
<p>Modifiers can help developers write cleaner, more modular code and make it easier to maintain and update their contracts.</p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Machine Learning Model in Rust ]]>
                </title>
                <description>
                    <![CDATA[ Machine learning is a really interesting concept in computer programming. It involves using data to train a computer program to carry out tasks.  During the process, the program learns from data by discovering patterns. This reduces the need for prog... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-machine-learning-model-in-rust/</link>
                <guid isPermaLink="false">66ba21e75ff1162736060bce</guid>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Rust ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oduah Chigozie ]]>
                </dc:creator>
                <pubDate>Wed, 12 Oct 2022 22:31:25 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/guerrillabuzz-crypto-pr-IlUq1ruyv0Q-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Machine learning is a really interesting concept in computer programming. It involves using data to train a computer program to carry out tasks. </p>
<p>During the process, the program learns from data by discovering patterns. This reduces the need for programmers to hard code rules in some applications.</p>
<p>Languages like Python and R are excellent for learning and carrying out machine learning tasks. But those languages aren’t absolute. They have weaknesses. Some machine learning applications may need to perform operations with great speed and computer resource efficiency.</p>
<p>Rust is a powerful and efficient programming language. Although Rust doesn’t have a mature ecosystem, the programming language’s nature makes it perfect for applications that require speed and efficiency.</p>
<p>Rust programmers will find this tutorial useful in getting started with machine learning. And, machine learning engineers will find this tutorial useful in getting started with machine learning on Rust.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along with this tutorial you’ll need the following:</p>
<ul>
<li>Knowledge of Rust</li>
<li>Rust installed in your system</li>
</ul>
<h2 id="heading-what-is-machine-learning">What is Machine Learning?</h2>
<p>In machine learning, a <strong>model</strong> is a software object that can understand patterns from data. Training a model is the process of giving data to the model to draw out patterns. Machine learning is the process of training a model to carry out tasks.</p>
<p>Once you've trained your model, you can use it to draw conclusions from new data. You can either base those conclusions on classifications or predictions. A predictive model uses current data to predict an event, result, or outcome. A classification model uses data to classify an object, or concept.</p>
<p>The following diagram is a basic overview of  the machine learning process:</p>
<p><img src="https://lh5.googleusercontent.com/0KA34Lh8SisIZvoBzmMm68mXoyPpcnpahY22r6l0tvF3GLcxeWuDcjhYHgN-3bVLdk2ow2KjrvnpCVoZS5Pd10TGoNymqmF2VyJBtHr8mZaoxnJ3xEtV6wPv_IwIefet3ve79PblWJzPGxhtuhln1gKUUc3Csg63rFfhCE7pjPVeRodJYotYop-h8Q" alt="Image" width="672" height="482" loading="lazy"></p>
<h2 id="heading-what-is-a-decision-tree">What is a Decision Tree?</h2>
<p>A decision tree algorithm is one of the most straightforward machine learning algorithms. This algorithm, unlike most other algorithms, gives a real sense of what machine learning is about.</p>
<p>A decision tree is a machine learning algorithm for classification and regression tasks. A decision tree is structured like a tree. It has a root node, internal nodes, leaf nodes, and branches. </p>
<p>The table below is an example of data that represents a classification of four animals with their properties:</p>
<table>
  <tbody><tr>
   <td>s/n
   </td>
   <td>Is wild
   </td>
   <td>Has round pupils
   </td>
   <td>Animal
   </td>
  </tr>
  <tr>
   <td>1
   </td>
   <td>True
   </td>
   <td>True
   </td>
   <td>Wolf
   </td>
  </tr>
  <tr>
   <td>2
   </td>
   <td>True
   </td>
   <td>False
   </td>
   <td>Tiger
   </td>
  </tr>
  <tr>
   <td>3
   </td>
   <td>False
   </td>
   <td>True
   </td>
   <td>Dog
   </td>
  </tr>
  <tr>
   <td>4
   </td>
   <td>False
   </td>
   <td>False
   </td>
   <td>Cat
   </td>
  </tr>
</tbody></table>

<p>A model recognizes the pattern(s) in the table, then creates a tree with this structure:</p>
<p><img src="https://lh5.googleusercontent.com/_nOsF4FkJgwcrTW19w8GT4DEtnm6_bvZ5pXXzh14TuXdeEoay9Tmv5dTaPhR7xhkbFLpX4EnmMHhw1GkIvg2GCcEw08rKbCm2cyubxpfaxoIawgRtuYSkRwy6tw-5Jl2ZgpxQ0r0uV6ww21DTXcANAdIJJHyDy2lIJsVqrjX78hOK4vn3XyIQEopIA" alt="Image" width="784" height="542" loading="lazy"></p>
<p>The root node is the first node in a decision tree. The leaf nodes are on the final line of the decision tree. The inner nodes are located between the root nodes and the leaf nodes. A decision tree can have more than one layer of inner nodes.</p>
<p>We'll use this algorithm in this article.</p>
<h2 id="heading-getting-started">Getting Started</h2>
<p>There are <a target="_blank" href="https://lib.rs/science/ml">a bunch of tools</a> that allow you to create machine learning applications in Rust. All the tools are great, but for this tutorial you’ll use <a target="_blank" href="https://rust-ml.github.io/linfa/">Linfa</a>. Linfa is a toolkit that is similar to the popular Python machine learning toolkit <a target="_blank" href="https://scikit-learn.org/">scikit-learn</a>.</p>
<p>In this section, you’ll learn how to set up a Rust project for machine learning. The process of setting up a project is relatively simple. All you need to do is follow these steps:</p>
<p>First, create a new project called <em>ml-project</em> with the following command:</p>
<pre><code class="lang-bash">cargo new --bin ml-project
</code></pre>
<p>Next, paste the following dependencies in <code>ml-project</code>’s <em>Cargo.toml</em> file, under <code>[dependencies]</code>:</p>
<pre><code class="lang-toml"><span class="hljs-attr">linfa</span> = <span class="hljs-string">"0.6.0"</span>
<span class="hljs-attr">linfa-trees</span> = <span class="hljs-string">"0.6.0"</span>
<span class="hljs-attr">linfa-datasets</span> = { version = <span class="hljs-string">"0.6.0"</span>, features = [<span class="hljs-string">"iris"</span>] }
</code></pre>
<p>Finally, run the following command to build the dependencies:</p>
<pre><code class="lang-bash">cargo build
</code></pre>
<p>The following is an explanation of the dependencies:</p>
<ul>
<li><code>linfa</code> is the base package for Linfa machine learning models.</li>
<li><code>linfa-trees</code> is a sub-package for building decision tree models.</li>
<li><code>linfa-datasets</code> is a package that provides already prepared datasets.</li>
</ul>
<p>The <code>linfa-datasets</code> package is optional. If you want to prepare your own dataset, follow the next section.</p>
<h2 id="heading-how-to-prepare-the-dataset">How to Prepare the Dataset</h2>
<p>Most machine learning models used in day-to-day projects are trained with external data, not the data provided by the toolkit. In this section, you’ll learn how to prepare your own dataset from a csv file.</p>
<p>First, you need to get a dataset if you don’t have one you can use. You can get a dataset from <a target="_blank" href="https://www.kaggle.com/">Kaggle</a>. For this tutorial, I’ll use the <a target="_blank" href="https://www.kaggle.com/datasets/yasserh/heart-disease-dataset">heart disease dataset</a>. The heart disease dataset looks like the below:</p>
<p><img src="https://lh3.googleusercontent.com/1Sc-Vza3H9Uy-6yg_LYqwrN8Sx9SITzX01wDXsvli09wYCYKFBHb9-QqwDX-_zU7whFh6b6lCa9ofyMQdy8WbZuLFQZJLolSqChhVsRwWH-beXwLgWoB7IuHJ2RBeFYF4Ef4_VOBvJQhKwknFMPDSAHttGBQGoWHJ27_clN2OPgxrklxafrmOc0vGg" alt="Image" width="564" height="359" loading="lazy"></p>
<p>In this dataset, <code>target</code> indicates that a person has heart disease. 1 means they have a heart disease, 0 means they do not have a heart disease.</p>
<p>The rest of the fields on the dataset are details of each person. A model can learn from this dataset and be able to tell if a person has a heart disease or not.</p>
<p>Once you have downloaded the dataset, extract the csv file into your project’s <em>src</em> folder.</p>
<pre><code class="lang-text">.
├── Cargo.lock
├── Cargo.toml
└── src
    ├── heart.csv
    └── main.rs
</code></pre>
<p>To prepare a dataset, you’ll need to add the <code>csv</code> and <code>ndarray</code> packages to your project. Open <em>Cargo.toml</em>, and write the following under <code>[dependencies]</code>:</p>
<pre><code class="lang-toml"><span class="hljs-attr">csv</span> = <span class="hljs-string">"1.1"</span>
<span class="hljs-attr">ndarray</span> = <span class="hljs-string">"0.15.6"</span>
</code></pre>
<p>Now, run <code>cargo build</code> to download the packages, and you are ready to go.</p>
<p>In the coming steps, I’ll guide you through building a <code>get_dataset</code> function. The <code>get_dataset</code> function reads the <em>heart.csv</em> file, parses its content, prepares a dataset with its contents, and returns the prepared dataset. Let’s get started!</p>
<p>First, import the necessary packages:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> csv::Reader;
<span class="hljs-keyword">use</span> std::fs::File;
<span class="hljs-keyword">use</span> ndarray::{ Array, Array1, Array2 };
<span class="hljs-keyword">use</span> linfa::Dataset;
</code></pre>
<p>Next, write the <code>get_dataset</code> function below into <em>main.rs</em>:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_dataset</span></span>() -&gt; Dataset&lt;<span class="hljs-built_in">f32</span>, <span class="hljs-built_in">i32</span>, ndarray::Dim&lt;[<span class="hljs-built_in">usize</span>; <span class="hljs-number">1</span>]&gt;&gt; {
 <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> reader = Reader::from_path(<span class="hljs-string">"./src/heart.csv"</span>).unwrap();

 <span class="hljs-keyword">let</span> headers = get_headers(&amp;<span class="hljs-keyword">mut</span> reader);
 <span class="hljs-keyword">let</span> data = get_data(&amp;<span class="hljs-keyword">mut</span> reader);
 <span class="hljs-keyword">let</span> target_index = headers.len() - <span class="hljs-number">1</span>;

 <span class="hljs-keyword">let</span> features = headers[<span class="hljs-number">0</span>..target_index].to_vec();
 <span class="hljs-keyword">let</span> records = get_records(&amp;data, target_index);
 <span class="hljs-keyword">let</span> targets = get_targets(&amp;data, target_index);

 <span class="hljs-keyword">return</span> Dataset::new(records, targets)
   .with_feature_names(features);
}
</code></pre>
<p>Finally, finish up by adding the definitions for <code>get_headers</code>, <code>get_data</code>, <code>get_records</code>, and <code>get_targets</code>:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_headers</span></span>(reader: &amp;<span class="hljs-keyword">mut</span> Reader&lt;File&gt;) -&gt; <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">String</span>&gt; {
 <span class="hljs-keyword">return</span> reader
   .headers().unwrap().iter()
   .map(|r| r.to_owned())
   .collect();
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_records</span></span>(data: &amp;<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">f32</span>&gt;&gt;, target_index: <span class="hljs-built_in">usize</span>) -&gt; Array2&lt;<span class="hljs-built_in">f32</span>&gt; {
 <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> records: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">f32</span>&gt; = <span class="hljs-built_in">vec!</span>[];
 <span class="hljs-keyword">for</span> record <span class="hljs-keyword">in</span> data.iter() {
   records.extend_from_slice( &amp;record[<span class="hljs-number">0</span>..target_index] );
 }
 <span class="hljs-keyword">return</span> Array::from( records ).into_shape((<span class="hljs-number">303</span>, <span class="hljs-number">13</span>)).unwrap();
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_targets</span></span>(data: &amp;<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">f32</span>&gt;&gt;, target_index: <span class="hljs-built_in">usize</span>) -&gt; Array1&lt;<span class="hljs-built_in">i32</span>&gt; {
 <span class="hljs-keyword">let</span> targets = data
   .iter()
   .map(|record| record[target_index] <span class="hljs-keyword">as</span> <span class="hljs-built_in">i32</span>)
   .collect::&lt;<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt;&gt;();
  <span class="hljs-keyword">return</span> Array::from( targets );
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_data</span></span>(reader: &amp;<span class="hljs-keyword">mut</span> Reader&lt;File&gt;) -&gt; <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">f32</span>&gt;&gt; {
 <span class="hljs-keyword">return</span> reader
   .records()
   .map(|r|
     r
       .unwrap().iter()
       .map(|field| field.parse::&lt;<span class="hljs-built_in">f32</span>&gt;().unwrap())
       .collect::&lt;<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">f32</span>&gt;&gt;()
   )
   .collect::&lt;<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">f32</span>&gt;&gt;&gt;();
}
</code></pre>
<p>Here’s a step-by-step explanation of the <code>get_dataset</code> function:</p>
<p>First, initialize a reader pointing to <em>./src/heart.csv</em>:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> reader = Reader::from_path(<span class="hljs-string">"./src/heart.csv"</span>).unwrap();
</code></pre>
<p>Next, extract the headers and data from <code>reader</code>:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> headers = get_headers(&amp;<span class="hljs-keyword">mut</span> reader);
<span class="hljs-keyword">let</span> data = get_data(&amp;<span class="hljs-keyword">mut</span> reader);
</code></pre>
<p>Then, calculate the index of <code>target</code> in the headers:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> target_index = headers.len() - <span class="hljs-number">1</span>;
</code></pre>
<p>After that, get the features from <code>headers</code>:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> features = headers[<span class="hljs-number">0</span>..target_index].to_vec();
</code></pre>
<p>Next, retrieve the records and targets from <code>data</code>:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> records = get_records(&amp;data, target_index);
<span class="hljs-keyword">let</span> targets = get_targets(&amp;data, target_index);
</code></pre>
<p>Finally, build the dataset with <code>records</code>, <code>targets</code>, and <code>features</code>, then return:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">return</span> Dataset::new(records, targets)
   .with_feature_names(features);
</code></pre>
<p>To finish up the function and to see how the dataset looks, make the following your <code>main</code> 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> dataset = get_dataset();
   <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, dataset);
}
</code></pre>
<p>Once you make that your main function and run it with <code>cargo run</code>, you’ll see the dataset in the output:</p>
<pre><code class="lang-rust">DatasetBase { records: [[<span class="hljs-number">63.0</span>, <span class="hljs-number">1.0</span>, <span class="hljs-number">3.0</span>, <span class="hljs-number">145.0</span>, <span class="hljs-number">233.0</span>, ..., <span class="hljs-number">0.0</span>, <span class="hljs-number">2.3</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">1.0</span>],
 [<span class="hljs-number">37.0</span>, <span class="hljs-number">1.0</span>, <span class="hljs-number">2.0</span>, <span class="hljs-number">130.0</span>, <span class="hljs-number">250.0</span>, ..., <span class="hljs-number">0.0</span>, <span class="hljs-number">3.5</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">2.0</span>],
 [<span class="hljs-number">41.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">1.0</span>, <span class="hljs-number">130.0</span>, <span class="hljs-number">204.0</span>, ..., <span class="hljs-number">0.0</span>, <span class="hljs-number">1.4</span>, <span class="hljs-number">2.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">2.0</span>],
 [<span class="hljs-number">56.0</span>, <span class="hljs-number">1.0</span>, <span class="hljs-number">1.0</span>, <span class="hljs-number">120.0</span>, <span class="hljs-number">236.0</span>, ..., <span class="hljs-number">0.0</span>, <span class="hljs-number">0.8</span>, <span class="hljs-number">2.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">2.0</span>],
 [<span class="hljs-number">57.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">120.0</span>, <span class="hljs-number">354.0</span>, ..., <span class="hljs-number">1.0</span>, <span class="hljs-number">0.6</span>, <span class="hljs-number">2.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">2.0</span>],
 ...,
 [<span class="hljs-number">57.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">140.0</span>, <span class="hljs-number">241.0</span>, ..., <span class="hljs-number">1.0</span>, <span class="hljs-number">0.2</span>, <span class="hljs-number">1.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">3.0</span>],
 [<span class="hljs-number">45.0</span>, <span class="hljs-number">1.0</span>, <span class="hljs-number">3.0</span>, <span class="hljs-number">110.0</span>, <span class="hljs-number">264.0</span>, ..., <span class="hljs-number">0.0</span>, <span class="hljs-number">1.2</span>, <span class="hljs-number">1.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">3.0</span>],
 [<span class="hljs-number">68.0</span>, <span class="hljs-number">1.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">144.0</span>, <span class="hljs-number">193.0</span>, ..., <span class="hljs-number">0.0</span>, <span class="hljs-number">3.4</span>, <span class="hljs-number">1.0</span>, <span class="hljs-number">2.0</span>, <span class="hljs-number">3.0</span>],
 [<span class="hljs-number">57.0</span>, <span class="hljs-number">1.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">130.0</span>, <span class="hljs-number">131.0</span>, ..., <span class="hljs-number">1.0</span>, <span class="hljs-number">1.2</span>, <span class="hljs-number">1.0</span>, <span class="hljs-number">1.0</span>, <span class="hljs-number">3.0</span>],
 [<span class="hljs-number">57.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">1.0</span>, <span class="hljs-number">130.0</span>, <span class="hljs-number">236.0</span>, ..., <span class="hljs-number">0.0</span>, <span class="hljs-number">0.0</span>, <span class="hljs-number">1.0</span>, <span class="hljs-number">1.0</span>, <span class="hljs-number">2.0</span>]], shape=[<span class="hljs-number">303</span>, <span class="hljs-number">13</span>], strides=[<span class="hljs-number">13</span>, <span class="hljs-number">1</span>], layout=Cc (<span class="hljs-number">0x5</span>), <span class="hljs-keyword">const</span> ndim=<span class="hljs-number">2</span>, targets: [<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>], shape=[<span class="hljs-number">303</span>], strides=[<span class="hljs-number">1</span>], layout=CFcf (<span class="hljs-number">0xf</span>), <span class="hljs-keyword">const</span> ndim=<span class="hljs-number">1</span>, weights: [], shape=[<span class="hljs-number">0</span>], strides=[<span class="hljs-number">0</span>], layout=CFcf (<span class="hljs-number">0xf</span>), <span class="hljs-keyword">const</span> ndim=<span class="hljs-number">1</span>, feature_names: [<span class="hljs-string">"age"</span>, <span class="hljs-string">"sex"</span>, <span class="hljs-string">"cp"</span>, <span class="hljs-string">"trestbps"</span>, <span class="hljs-string">"chol"</span>, <span class="hljs-string">"fbs"</span>, <span class="hljs-string">"restecg"</span>, <span class="hljs-string">"thalach"</span>, <span class="hljs-string">"exang"</span>, <span class="hljs-string">"oldpeak"</span>, <span class="hljs-string">"slope"</span>, <span class="hljs-string">"ca"</span>, <span class="hljs-string">"thal"</span>] }
</code></pre>
<h2 id="heading-how-to-create-a-decision-tree-model">How to Create a Decision Tree Model</h2>
<p>In this section, I’ll show you how to create a decision tree model and train it. The dataset I’ll use is the iris dataset provided by <code>linfa-datasets</code>. </p>
<p>The iris dataset contains a record of the sepal width, sepal height, petal width, and petal height of several irises, and classifies each record according to number-labeled species.</p>
<p>The code for the model is simple. Open the <em>main.rs</em> file, and paste the following into it:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> linfa_trees::DecisionTree;
<span class="hljs-keyword">use</span> linfa::prelude::*;

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> (train, test) = linfa_datasets::iris()
        .split_with_ratio(<span class="hljs-number">0.9</span>);

    <span class="hljs-keyword">let</span> model = DecisionTree::params()
        .fit(&amp;train).unwrap();

    <span class="hljs-keyword">let</span> predictions = model.predict(&amp;test);

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, predictions);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, test.targets);
}
</code></pre>
<p>Here's an explanation:</p>
<p>First, import the necessary packages:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> linfa_trees::DecisionTree;
<span class="hljs-keyword">use</span> linfa::prelude::*;
</code></pre>
<p>Next, fetch the dataset, and split into testing and training data:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> (train, test) = linfa_datasets::iris()
    .split_with_ratio(<span class="hljs-number">0.9</span>);
</code></pre>
<p>After that, initialize the model and train it with the training data:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> model = DecisionTree::params()
    .fit(&amp;train).unwrap();
</code></pre>
<p>Then, use the testing data to make some predictions:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> predictions = model.predict(&amp;test);
</code></pre>
<p>Finally, compare the predictions with the actual values:</p>
<pre><code class="lang-rust"><span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, predictions);
<span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, test.targets);
</code></pre>
<p>If you run the program with <code>cargo run</code>, you’ll get the predicted category and the actual category in the terminal as output:</p>
<pre><code class="lang-rust">$ cargo run
[<span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>], shape=[<span class="hljs-number">15</span>], strides=[<span class="hljs-number">1</span>], layout=CFcf (<span class="hljs-number">0xf</span>), <span class="hljs-keyword">const</span> ndim=<span class="hljs-number">1</span>
[<span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>], shape=[<span class="hljs-number">15</span>], strides=[<span class="hljs-number">1</span>], layout=CFcf (<span class="hljs-number">0xf</span>), <span class="hljs-keyword">const</span> ndim=<span class="hljs-number">1</span>
</code></pre>
<p>From the above, you can see that this model is 100% accurate. This won’t always be the case for all machine learning models. If you shuffle the dataset before training the model in the above, the model may not be as accurate anymore. </p>
<p>The goal of machine learning is to be as accurate as possible. Most times 100% accuracy is not possible.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you learnt a little about machine learning, and you also saw how to create a decision tree model using Rust. </p>
<p>Machine learning models in Linfa follow a similar process in building and training, so all you need to do to use other types of models is to learn about each one, and you are good to go. </p>
<p>You can learn more about Linfa and the models it supports using <a target="_blank" href="https://docs.rs/linfa/latest/linfa/">its documentation</a>.</p>
<p>Thanks for reading, and happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
