<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Kelvin Kirima</title>
    <description>The latest articles on Forem by Kelvin Kirima (@kelvinkirima014).</description>
    <link>https://forem.com/kelvinkirima014</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F494807%2F9d9ab522-69c0-4174-b7ec-45679d102e51.jpeg</url>
      <title>Forem: Kelvin Kirima</title>
      <link>https://forem.com/kelvinkirima014</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/kelvinkirima014"/>
    <language>en</language>
    <item>
      <title>The Mechanics of mutable and immutable references in Rust</title>
      <dc:creator>Kelvin Kirima</dc:creator>
      <pubDate>Fri, 09 Feb 2024 21:42:00 +0000</pubDate>
      <link>https://forem.com/kelvinkirima014/the-mechanics-of-mutable-and-immutable-references-in-rust-2207</link>
      <guid>https://forem.com/kelvinkirima014/the-mechanics-of-mutable-and-immutable-references-in-rust-2207</guid>
      <description>&lt;p&gt;The design choices of a programming language have direct implications on how we write code. One such design choice is the concept of ownership and borrowing in the Rust programming language. &lt;/p&gt;

&lt;h2&gt;
  
  
  Ownership, References and Immutability
&lt;/h2&gt;

&lt;p&gt;Stated simply, the concept of ownership deems that we can only have one owner of a value at a time, this value can be passed around severally for read-only operations by immutably borrowing or referencing, but we can only have one mutable borrow at a time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;input&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;String&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;new&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="n"&gt;input&lt;/span&gt;&lt;span class="nf"&gt;.push_str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Hello World"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"input value is: {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;input&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;take_ownership&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;input&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Taken ownership of value {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;take_ownership&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;_illegal&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;input&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// throws an error -&amp;gt; use of moved value `input`&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The error message tells us we are trying to use a value which has already been moved to another memory location. When we create the variable &lt;code&gt;take_ownership&lt;/code&gt;, we move the value in the &lt;code&gt;input&lt;/code&gt;'s memory location to &lt;code&gt;take_ownership&lt;/code&gt;, thus trying to allocate &lt;code&gt;input&lt;/code&gt;'s value to another variable fails, because the value is no longer there. This is all by design, imagine if we were successful in having two variables own the value at the same time, and then have both variables mutate the value, we got ourselves a race condition, not good. Innit?&lt;/p&gt;

&lt;p&gt;There's a work-around to this that makes the error go away quickly; Instead of taking ownership, we just borrow the value&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;borrow_value&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;input&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"..."&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;another_borrow&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;input&lt;/span&gt;
&lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"..."&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The ampersand sign &lt;code&gt;&amp;amp;&lt;/code&gt; denotes that we are taking a reference to the memory address the value is stored, but we're not taking ownership of the value itself. Now we can have as many borrows as we want, but there's a catch: We can only have one mutable reference at a time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;borrow_value&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;input&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; 
&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;another_borrow&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;input&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you tried writing code like the one above, your Rust &lt;a href="https://microsoft.github.io/language-server-protocol/"&gt;LSP&lt;/a&gt; should already be telling you that what you're doing is unacceptable:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="n"&gt;error&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;E0499&lt;/span&gt;&lt;span class="p"&gt;]:&lt;/span&gt; &lt;span class="n"&gt;cannot&lt;/span&gt; &lt;span class="n"&gt;borrow&lt;/span&gt; &lt;span class="n"&gt;input&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;mutable&lt;/span&gt; &lt;span class="n"&gt;more&lt;/span&gt; &lt;span class="n"&gt;than&lt;/span&gt; &lt;span class="n"&gt;once&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But it's possible to have another mutable borrow when the first borrow goes out of scope. The code below runs successfully because we create the variable &lt;code&gt;another_borrow&lt;/code&gt; after &lt;code&gt;borrow_value&lt;/code&gt; has already been used and it's scope ended.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;borrow_value&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;input&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;borrow_value&lt;/span&gt;&lt;span class="nf"&gt;.push_str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;" Changers"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;another_borrow&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;input&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"another_borrow: {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;another_borrow&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The reference's scope start from where it is introduced and continues through the last time that reference is used; when the reference goes out of scope, it's borrow ends, and the value becomes available for borrowing again. When all references to the value are gone, Rust frees the memory where the value is located.  These rules of ownership, borrowing and scope are what enables Rust to be able to allocate and free memory safely without a garbage collector, how practical!&lt;/p&gt;

&lt;h2&gt;
  
  
  Dereferencing
&lt;/h2&gt;

&lt;p&gt;We've established that references do not hold any values by themselves, instead they point to the location in memory where the actual value is stored. Now, what if we want to modify the actual value the reference is pointing at? Take this simple example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;ref_val&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Imagine that we want to change the &lt;code&gt;ref_value&lt;/code&gt; to 30; to a new Rustacean, the first thought would be to do something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;ref_val&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="n"&gt;ref_val&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Trying to write the above code will have the compiler sympathizing with us:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;error[E0308]: mismatched types
  &lt;span class="nt"&gt;--&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; src/main.rs:20:17
   |
|     &lt;span class="nb"&gt;let &lt;/span&gt;ref_value &lt;span class="o"&gt;=&lt;/span&gt; &amp;amp;mut value&lt;span class="p"&gt;;&lt;/span&gt;
   |                     &lt;span class="nt"&gt;----------&lt;/span&gt; expected due to this value
|     ref_value &lt;span class="o"&gt;=&lt;/span&gt; 30&lt;span class="p"&gt;;&lt;/span&gt;
   |                 ^^ expected &amp;amp;mut &lt;span class="o"&gt;{&lt;/span&gt;integer&lt;span class="o"&gt;}&lt;/span&gt;, found integer
   |
&lt;span class="nb"&gt;help&lt;/span&gt;: consider dereferencing here to assign to the mutably borrowed value
   |
 |     &lt;span class="k"&gt;*&lt;/span&gt;ref_value &lt;span class="o"&gt;=&lt;/span&gt; 30&lt;span class="p"&gt;;&lt;/span&gt;
   |     +
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I encourage you to take a minute and read the error message keenly. We get the error because &lt;code&gt;ref_value&lt;/code&gt; holds the reference to the value, and not the value itself; in other terms, we are trying to assign to the reference, and not the value it points to, and Rust does not allow us to assign directly to the reference because this would mutate the actual value. So, what do we do? The compiler has already helped us with that. To assign the integer to the actual value, we need to &lt;em&gt;dereference&lt;/em&gt;&lt;code&gt;ref_value&lt;/code&gt; and access the actual value behind it; we do this using the unary operator&lt;code&gt;*&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;ref_val&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;ref_val&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One question you may already have is why we didn't have to do that with the &lt;code&gt;push_str&lt;/code&gt; operations earlier:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;borrow_value&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;input&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="n"&gt;borrow_value&lt;/span&gt;&lt;span class="nf"&gt;.push_str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;" Changers"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's because when we use the dot operator, the expression on the left-hand side of the dot is auto-referenced/auto-derefenced automatically. You can read more about the dot-operator &lt;a href="https://doc.rust-lang.org/nomicon/dot-operator.html"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  A more Interesting Problem
&lt;/h2&gt;

&lt;p&gt;This article was inspired by a problem I encountered while working with the &lt;a href="https://docs.rs/sqlx/latest/sqlx/index.html"&gt;sqlx&lt;/a&gt; library; I wanted to have a database connection that I can reuse across multiple queries. Sqlx has a &lt;code&gt;begin&lt;/code&gt; method that creates a database connection and immediately begins a new transaction, so what I need to do is figure out how to compose multi-statement transactions with it. My first attempt looks like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;demo_txn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;PgPool&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Result&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;tx&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="nf"&gt;.begin&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="k"&gt;.await&lt;/span&gt;&lt;span class="nf"&gt;.map_errr&lt;/span&gt;&lt;span class="p"&gt;(|&lt;/span&gt;&lt;span class="n"&gt;err&lt;/span&gt;&lt;span class="p"&gt;|&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nd"&gt;error!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"error starting database transaction: {err}"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;span class="err"&gt;`&lt;/span&gt;
    &lt;span class="p"&gt;})&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;sqlx&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"..."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="nf"&gt;.fetch_one&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;tx&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="k"&gt;.await&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nn"&gt;sqlx&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"..."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="nf"&gt;.execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="n"&gt;tx&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="k"&gt;.await&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Above, I create a transaction, and then try to consume a mutable reference to the transaction in my queries; however, the code throws this error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;error[E0277]: the trait bound &amp;amp;mut Transaction&amp;lt;&lt;span class="s1"&gt;'_, Postgres&amp;gt;: sqlx::Executor
&amp;lt;'&lt;/span&gt;_&amp;gt; is not satisfied
   &lt;span class="nt"&gt;--&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; src/routes/signup.rs:117:14
    |
 |     .execute&lt;span class="o"&gt;(&lt;/span&gt;&amp;amp;mut tx&lt;span class="o"&gt;)&lt;/span&gt;
    |      &lt;span class="nt"&gt;-------&lt;/span&gt; ^^^^^^^ the trait sqlx::Executor&amp;lt;&lt;span class="s1"&gt;'_&amp;gt; is not implemented 
for &amp;amp;mut Transaction&amp;lt;'&lt;/span&gt;_, Postgres&amp;gt;
    |      |
    |      required by a bound introduced by this call
    |
    &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;help&lt;/span&gt;: the following other types implement trait sqlx::Executor&amp;lt;&lt;span class="s1"&gt;'c&amp;gt;:
              &amp;lt;&amp;amp;'&lt;/span&gt;c mut PgConnection as sqlx::Executor&amp;lt;&lt;span class="s1"&gt;'c&amp;gt;&amp;gt;
              &amp;lt;&amp;amp;'&lt;/span&gt;c mut PgListener as sqlx::Executor&amp;lt;&lt;span class="s1"&gt;'c&amp;gt;&amp;gt;
              &amp;lt;&amp;amp;'&lt;/span&gt;c mut AnyConnection as sqlx::Executor&amp;lt;&lt;span class="s1"&gt;'c&amp;gt;&amp;gt;
              &amp;lt;&amp;amp;Pool&amp;lt;DB&amp;gt; as sqlx::Executor&amp;lt;'&lt;/span&gt;p&amp;gt;&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The error tells us that the &lt;code&gt;sqlx::Executor&lt;/code&gt; trait, which provides a database connection we can use for executing queries is not implemented for our mutable reference to the &lt;code&gt;Transaction&lt;/code&gt; type. These are one of those errors that have you scratching your head because the compiler has no more help to offer you, we are basically on our own now. The logical thing to do here is to dig into other people's code and see if I can find out how others construct multi-statement transactions in sqlx. I came across a similar problem on Github, and the solution offered is to dereference the transaction:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;demo_txn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;PgPool&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Result&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;tx&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="nf"&gt;.begin&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="k"&gt;.await&lt;/span&gt;&lt;span class="nf"&gt;.map_errr&lt;/span&gt;&lt;span class="p"&gt;(|&lt;/span&gt;&lt;span class="n"&gt;err&lt;/span&gt;&lt;span class="p"&gt;|&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nd"&gt;error!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"error starting database transaction: {err}"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;})&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;sqlx&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"..."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="nf"&gt;.fetch_one&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;tx&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="k"&gt;.await&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// notice the *&lt;/span&gt;

    &lt;span class="nn"&gt;sqlx&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"..."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="nf"&gt;.execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;tx&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="k"&gt;.await&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;//notice *&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And true enough, the errors go away; Interesting, let's dig a little deeper to understand what's going on. The &lt;code&gt;begin&lt;/code&gt; method we call on the &lt;code&gt;db&lt;/code&gt; looks like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;begin&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Result&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Transaction&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;'static&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;DB&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;Error&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we call &lt;code&gt;?&lt;/code&gt; on the Result, we are left with the &lt;code&gt;Transaction&lt;/code&gt; type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;Transaction&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nv"&gt;'c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;DB&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="k"&gt;where&lt;/span&gt;
    &lt;span class="n"&gt;DB&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Database&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="o"&gt;...&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, when we do &lt;code&gt;*tx&lt;/code&gt;, we are asking for a mutable dereference to the &lt;code&gt;Transaction&lt;/code&gt; because our methods are in a mutable expression context. Rust requires that types that want to be dereferenced implement the &lt;a href="https://doc.rust-lang.org/std/ops/trait.Deref.html#"&gt;Deref&lt;/a&gt; trait - for immutable dereference, or the &lt;a href="https://doc.rust-lang.org/std/ops/trait.DerefMut.html"&gt;DerefMut&lt;/a&gt; trait for mutable dereferences. The transaction type implements both of these traits, here's the DerefMut implementation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="k"&gt;impl&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nv"&gt;'c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;DB&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;DerefMut&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;Transaction&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nv"&gt;'c&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;DB&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="k"&gt;where&lt;/span&gt;
    &lt;span class="n"&gt;DB&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Database&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;#[inline]&lt;/span&gt;
    &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;deref_mut&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="k"&gt;Self&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Target&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.connection&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;*&lt;/code&gt; uses the above &lt;code&gt;DerefMut&lt;/code&gt; implementation and yields a mutable &lt;code&gt;&amp;lt;DB as Database&amp;gt;::Connection&lt;/code&gt; (the associated connection type for whichever DB we're using). I'm using Postgres, so the deref gets us a mutable &lt;a href="https://docs.rs/sqlx/latest/sqlx/struct.PgConnection.html"&gt;PgConnection&lt;/a&gt; which implements the &lt;code&gt;sqlx::Executor&lt;/code&gt; trait that was missing and thus causing the compilation error. &lt;/p&gt;

&lt;p&gt;I understand this has been a long exposition, but an example like this goes to show how some of the errors we may encounter even with trait bound issues are directly tied to the concepts of ownership and references - and how deep they can go.&lt;/p&gt;

&lt;h2&gt;
  
  
  Finishing Up
&lt;/h2&gt;

&lt;p&gt;Thanks for reading! I hope this article has helped shine some light on arguably some of the most important Rust concepts. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;This post was first published at &lt;a href="https://kelvinkirima.com/"&gt;https://kelvinkirima.com/&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>rust</category>
      <category>programming</category>
    </item>
    <item>
      <title>Generating the nth Fibonacci in Rust.</title>
      <dc:creator>Kelvin Kirima</dc:creator>
      <pubDate>Wed, 14 Jul 2021 22:05:49 +0000</pubDate>
      <link>https://forem.com/kelvinkirima014/generating-the-nth-fibonacci-in-rust-238k</link>
      <guid>https://forem.com/kelvinkirima014/generating-the-nth-fibonacci-in-rust-238k</guid>
      <description>&lt;h3&gt;
  
  
  What’s a Fibonacci sequence?
&lt;/h3&gt;

&lt;p&gt;Fibonacci numbers are numbers that form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1.&lt;br&gt;&lt;br&gt;
The Fibonacci sequence&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Written as an expression, &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Fn = Fn-1 + Fn-2&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Getting Started.
&lt;/h3&gt;

&lt;p&gt;You need to have Rust installed on your computer, for Linux or macOS run the following command in your terminal,&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If the install is successful, the following line will appear:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Rust is installed now. Great!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For those on windows, see the &lt;a href="https://www.rust-lang.org/tools/install" rel="noopener noreferrer"&gt;Rust docs&lt;/a&gt;.&lt;br&gt;
Now run this command to create a new Rust project.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

cargo new rust_fibonacci


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Then&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

cd rust_fibonacci


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Open the directory in your IDE&lt;br&gt;
You’ll find that Rust generates a &lt;code&gt;main.rs&lt;/code&gt; file for you, this is our entry point to Rust, open the file. It looks like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;“&lt;span class="n"&gt;Hello&lt;/span&gt; &lt;span class="n"&gt;world&lt;/span&gt;”&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now let’s go ahead and edit the code..&lt;/p&gt;

&lt;h3&gt;
  
  
  Fibonacci Function
&lt;/h3&gt;

&lt;p&gt;Let’s create a function below the &lt;code&gt;main&lt;/code&gt; function that  generates a fibonacci sequence&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;fib&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;i32&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;i32&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
          &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
          &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;fib&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nf"&gt;fib&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
 &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here is what’s happening. First, we create a function (fn) named &lt;code&gt;fib&lt;/code&gt; and pass variable &lt;code&gt;n&lt;/code&gt; as a parameter. In Rust, we have to specify the type of the parameter and its return value. I specify it’s a &lt;code&gt;u32&lt;/code&gt;, meaning it can only accept unsigned/positive integers of 32 bits and the &lt;code&gt;-&amp;gt;&lt;/code&gt; is specifying the return type of the function which is also a &lt;code&gt;u32&lt;/code&gt; integer. &lt;br&gt;
Next, I use an &lt;code&gt;if&lt;/code&gt; expression followed by a condition that checks if the value of &lt;code&gt;n&lt;/code&gt; is less or equal to &lt;code&gt;0&lt;/code&gt; and returns &lt;code&gt;0&lt;/code&gt; if that’s the case. We then check to see if the value of &lt;code&gt;n&lt;/code&gt; is &lt;code&gt;1&lt;/code&gt; and return &lt;code&gt;1&lt;/code&gt;. In the &lt;code&gt;else&lt;/code&gt; part, we implement the logic of the Fibonacci sequence by recursively calling the function with a different integer.&lt;/p&gt;

&lt;h3&gt;
  
  
  Printing the Values on the screen.
&lt;/h3&gt;

&lt;p&gt;Now let’s go back to our &lt;code&gt;main&lt;/code&gt; function and modify it to look like this...&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt; &lt;span class="p"&gt;){&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;..&lt;/span&gt;&lt;span class="mi"&gt;15&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
         &lt;span class="nd"&gt;println!&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt; “&lt;span class="nf"&gt;fibonacci&lt;/span&gt; &lt;span class="p"&gt;({})&lt;/span&gt; &lt;span class="k"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;”&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;fib&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
     &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Inside the &lt;code&gt;main&lt;/code&gt; function is a &lt;a href="https://doc.rust-lang.org/rust-by-example/flow_control/for.html" rel="noopener noreferrer"&gt;for&lt;/a&gt; loop that loops over every integer from 0 to 15 and we use the &lt;code&gt;println!&lt;/code&gt; to print each integer we pass and its corresponding Fibonacci value.&lt;br&gt;
Type &lt;code&gt;cargo run&lt;/code&gt; in your terminal and the output should look like this...&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flfg9wbkdj95n860i4dci.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flfg9wbkdj95n860i4dci.png" alt="fibonacci"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Accept User Input.
&lt;/h3&gt;

&lt;p&gt;We want our program to allow the user to input a number and gets its corresponding Fibonacci. Edit the &lt;code&gt;main&lt;/code&gt; function to look like so,&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

&lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="nn"&gt;std&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;io&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt; &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;println!&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;“&lt;span class="n"&gt;To&lt;/span&gt; &lt;span class="n"&gt;quit&lt;/span&gt; &lt;span class="n"&gt;the&lt;/span&gt; &lt;span class="n"&gt;program&lt;/span&gt; &lt;span class="k"&gt;type&lt;/span&gt; `&lt;span class="n"&gt;exit&lt;/span&gt;` “&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;loop&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
         &lt;span class="nd"&gt;println!&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;“&lt;span class="n"&gt;TYPE&lt;/span&gt; &lt;span class="n"&gt;A&lt;/span&gt; &lt;span class="n"&gt;POSITIVE&lt;/span&gt; &lt;span class="n"&gt;NUMBER&lt;/span&gt;”&lt;span class="p"&gt;)&lt;/span&gt;
         &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;String&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;new&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
         &lt;span class="nn"&gt;io&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;stdin&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt; &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nf"&gt;.read_line&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nf"&gt;.expect&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="err"&gt;“&lt;/span&gt;&lt;span class="n"&gt;Failed&lt;/span&gt; &lt;span class="n"&gt;to&lt;/span&gt; &lt;span class="n"&gt;read&lt;/span&gt; &lt;span class="n"&gt;your&lt;/span&gt; &lt;span class="n"&gt;input&lt;/span&gt;&lt;span class="err"&gt;”&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="nf"&gt;.trim&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt; &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="err"&gt;“&lt;/span&gt;&lt;span class="n"&gt;exit&lt;/span&gt;&lt;span class="err"&gt;”&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;break&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;u32&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;match&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="nf"&gt;.trim&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
         &lt;span class="nf"&gt;.parse&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
          &lt;span class="nf"&gt;Ok&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
          &lt;span class="nf"&gt;Err&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;continue&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
          &lt;span class="p"&gt;};&lt;/span&gt;
        &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Fibonacci ({}) =&amp;gt; {}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; 
        &lt;span class="nf"&gt;fib&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;    
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Let’s go over the above code line by line. &lt;br&gt;
First, we import a library that allows us to handle user input.&lt;br&gt;
&lt;code&gt;use std::io;&lt;/code&gt;&lt;br&gt;
Rust brings only a few types into the scope of every program in the &lt;a href="https://doc.rust-lang.org/std/prelude/index.html" rel="noopener noreferrer"&gt;prelude&lt;/a&gt;. If a type you want to use isn’t in the prelude, bring that type into scope explicitly with a &lt;code&gt;use&lt;/code&gt; statement. &lt;br&gt;
Inside the &lt;code&gt;main&lt;/code&gt; function, we first let the user know how to quit the program by using the println! Macro to print a string to the screen.&lt;/p&gt;

&lt;h3&gt;
  
  
  Inside the Loop.
&lt;/h3&gt;

&lt;p&gt;Next, we create a &lt;a href="https://doc.rust-lang.org/rust-by-example/flow_control/loop.html" rel="noopener noreferrer"&gt;loop&lt;/a&gt; using the &lt;code&gt;loop&lt;/code&gt; keyword that will keep running until you break out by typing &lt;em&gt;exit&lt;/em&gt;(we’ll see how that happens in a moment). We then let the user know how to interact with the game each loop by using &lt;code&gt;println!&lt;/code&gt; again to print a string on the screen.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

         &lt;span class="nd"&gt;println!&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;“&lt;span class="n"&gt;TYPE&lt;/span&gt; &lt;span class="n"&gt;A&lt;/span&gt; &lt;span class="n"&gt;POSITIVE&lt;/span&gt; &lt;span class="n"&gt;NUMBER&lt;/span&gt;”&lt;span class="p"&gt;);&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  variables and mutability
&lt;/h3&gt;

&lt;p&gt;Each time through the loop, we create a mutable variable called &lt;code&gt;int&lt;/code&gt;&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;String&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;new&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Variables in Rust are immutable by default so we have to add the &lt;code&gt;mut&lt;/code&gt; keyword when we are creating a mutable variable. &lt;br&gt;
On the other side of the equal sign &lt;code&gt;(=)&lt;/code&gt; is the value that &lt;code&gt;int&lt;/code&gt; is bound to, which is the result of calling &lt;code&gt;String::new&lt;/code&gt;, a function that returns a new instance of a String. So, what we are doing is creating a mutable variable that is currently bound to a new, empty instance of a String. &lt;br&gt;
We then use the &lt;code&gt;std::io&lt;/code&gt; library that we imported by calling the &lt;code&gt;stdin&lt;/code&gt; function from the &lt;code&gt;io&lt;/code&gt;module…&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

  &lt;span class="nn"&gt;io&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;stdin&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt; &lt;span class="p"&gt;)&lt;/span&gt;
     &lt;span class="nf"&gt;.read_line&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The next line, &lt;code&gt;.read_line(&amp;amp;mut int)&lt;/code&gt;, calls the &lt;code&gt;read_line&lt;/code&gt; method on the standard input handle to get input from the user.&lt;code&gt;read_line&lt;/code&gt; takes whatever the user types  into standard input and append that into a string. We’re also passing one argument &lt;code&gt;( &amp;amp;mut int)&lt;/code&gt;to the method. The &lt;code&gt;&amp;amp;&lt;/code&gt; indicates that the argument is a &lt;a href="https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html" rel="noopener noreferrer"&gt;reference&lt;/a&gt;, &lt;em&gt;references&lt;/em&gt; are also immutable by default so you need to write  &lt;code&gt;&amp;amp;mut int&lt;/code&gt; to make it mutable.&lt;/p&gt;

&lt;p&gt;The next part is this method:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

&lt;span class="nf"&gt;.expect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Failed to read line"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Is a Result type that represents either success (Ok) or failure (Err). AS I mentioned,&lt;code&gt;read_line&lt;/code&gt; puts what the user types into the string we’re passing it, but it also returns a value — in this case, an &lt;a href="https://doc.rust-lang.org/std/io/type.Result.html" rel="noopener noreferrer"&gt;io::Result&lt;/a&gt;. The &lt;a href="https://doc.rust-lang.org/std/result/enum.Result.html" rel="noopener noreferrer"&gt;Result&lt;/a&gt; types are enumerations/enums. An &lt;a href="https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html" rel="noopener noreferrer"&gt;enumeration&lt;/a&gt; is a type that can have a fixed set of values, and those values are called the enum’s variants.&lt;/p&gt;

&lt;p&gt;If this instance of &lt;code&gt;io::Result&lt;/code&gt; is an &lt;a href="https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err" rel="noopener noreferrer"&gt;Err&lt;/a&gt; value, &lt;a href="https://doc.rust-lang.org/std/result/enum.Result.html#method.expect" rel="noopener noreferrer"&gt;expect&lt;/a&gt; will cause the program to crash and display the message that you passed as an argument to &lt;code&gt;expect&lt;/code&gt;. If this instance of &lt;code&gt;io::Result&lt;/code&gt; is an &lt;a href="https://doc.rust-lang.org/std/result/enum.Result.html#variant.Ok" rel="noopener noreferrer"&gt;Ok&lt;/a&gt; value, &lt;code&gt;expect&lt;/code&gt; will take the return value that &lt;code&gt;Ok&lt;/code&gt; is holding and return just that value to you so you can use it.&lt;/p&gt;

&lt;p&gt;Our next piece of code is:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="nf"&gt;.trim&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt; &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="err"&gt;“&lt;/span&gt;&lt;span class="n"&gt;exit&lt;/span&gt;&lt;span class="err"&gt;”&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;break&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;That checks to see if a user types &lt;em&gt;exit&lt;/em&gt; to &lt;code&gt;break&lt;/code&gt; out of the program. The &lt;code&gt;.trim( )&lt;/code&gt; method is passed to eliminate any whitespace at the beginning and the end.&lt;br&gt;
In the next block of code,&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;i32&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;match&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="nf"&gt;.trim&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt; &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nf"&gt;.parse&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt; &lt;span class="p"&gt;){&lt;/span&gt; 
        &lt;span class="nf"&gt;Ok&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="k"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="nf"&gt;Err&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="k"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;continue&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
     &lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We create a variable named &lt;code&gt;int&lt;/code&gt;, Rust allows us to &lt;a href="https://en.wikipedia.org/wiki/Variable_shadowing" rel="noopener noreferrer"&gt;shadow&lt;/a&gt; the previous value of &lt;code&gt;int&lt;/code&gt; with a new one. We often use this feature in situations in which we want to convert a value from one type to another type.&lt;br&gt;
We bind &lt;code&gt;int&lt;/code&gt; to the expression &lt;code&gt;int.trim().parse()&lt;/code&gt;. The &lt;code&gt;int&lt;/code&gt; in the expression refers to the original &lt;code&gt;int&lt;/code&gt; that was a String with the input in it. The &lt;code&gt;.trim()&lt;/code&gt; method on a String instance will eliminate any whitespace at the beginning and end. We use the &lt;code&gt;.parse()&lt;/code&gt; method to turn the string into an integer.  &lt;code&gt;parse&lt;/code&gt; returns a &lt;em&gt;Result&lt;/em&gt; type and Result is an &lt;em&gt;enum&lt;/em&gt; that has the variants &lt;code&gt;Ok&lt;/code&gt; or &lt;code&gt;Err&lt;/code&gt;, remember? We use a &lt;a href="https://doc.rust-lang.org/rust-by-example/flow_control/match.html?highlight=match#match" rel="noopener noreferrer"&gt;&lt;code&gt;match&lt;/code&gt;&lt;/a&gt; expression to decide what to do next based on which variant of Result that was returned. If the user typed in a number, we get &lt;code&gt;Ok&lt;/code&gt; and store the number in &lt;code&gt;int&lt;/code&gt;. If not, we call &lt;code&gt;continue&lt;/code&gt; and instruct the user to pass in a positive integer again. The program basically ignores all errors that parse might encounter!&lt;br&gt;
We finally print each integer the user passes and its corresponding Fibonacci value.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

&lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;“&lt;span class="nf"&gt;fibonacci&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="p"&gt;})&lt;/span&gt; &lt;span class="k"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;”&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;fib&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The entire code should now look like this,&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;

&lt;p&gt;&lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="nn"&gt;std&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;io&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;br&gt;
&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;br&gt;
   &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"To end the program, type &lt;code&gt;exit&lt;/code&gt; "&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;br&gt;
   &lt;span class="k"&gt;loop&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;br&gt;
       &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Type a positive integer"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;br&gt;
       &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;String&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;new&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;&lt;br&gt;
        &lt;span class="nn"&gt;io&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;stdin&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;br&gt;
       &lt;span class="nf"&gt;.read_line&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="k"&gt;mut&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;br&gt;
       &lt;span class="nf"&gt;.expect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;""&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;&lt;br&gt;
       &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="nf"&gt;.trim&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s"&gt;"exit"&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;br&gt;
           &lt;span class="k"&gt;break&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;br&gt;
       &lt;span class="p"&gt;}&lt;/span&gt;&lt;br&gt;
       &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;u32&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;match&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="nf"&gt;.trim&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;br&gt;
       &lt;span class="nf"&gt;.parse&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;br&gt;
           &lt;span class="nf"&gt;Ok&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;br&gt;
           &lt;span class="nf"&gt;Err&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;_&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;continue&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;br&gt;
       &lt;span class="p"&gt;};&lt;/span&gt;&lt;br&gt;
       &lt;span class="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Fibonacci ({}) =&amp;gt; {}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;fib&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;fib&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;u32&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;u32&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;br&gt;
   &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;br&gt;
       &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;br&gt;
   &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;br&gt;
       &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;br&gt;
   &lt;span class="p"&gt;}&lt;/span&gt;   &lt;span class="nf"&gt;fib&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nf"&gt;fib&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;br&gt;
&lt;span class="p"&gt;}&lt;/span&gt;&lt;/p&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Conclusion&lt;br&gt;
&lt;/h3&gt;

&lt;p&gt;This was a great exploration of several Rust concepts like variables, loops, match, conditionals and data types. You could also go through the &lt;a href="https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html" rel="noopener noreferrer"&gt;guessing game&lt;/a&gt; in the Rust book which I borrowed most concepts of this program from. Am looking forward to tackling more challenges and building better programs.&lt;/p&gt;

&lt;p&gt;This blog was first published in &lt;a href="https://kirima.vercel.app/" rel="noopener noreferrer"&gt;my blog&lt;/a&gt;&lt;/p&gt;

</description>
      <category>rust</category>
      <category>beginners</category>
      <category>fibonacci</category>
      <category>webdev</category>
    </item>
    <item>
      <title>What Is The Javascript Event Loop?</title>
      <dc:creator>Kelvin Kirima</dc:creator>
      <pubDate>Sun, 21 Feb 2021 18:21:51 +0000</pubDate>
      <link>https://forem.com/kelvinkirima014/what-is-the-javascript-event-loop-588b</link>
      <guid>https://forem.com/kelvinkirima014/what-is-the-javascript-event-loop-588b</guid>
      <description>&lt;p&gt;Javascript is single-threaded,i.e, it executes only one operation at a time. This process of executing only one operation at a time on a single thread is the reason we say javascript is &lt;strong&gt;synchronous&lt;/strong&gt;. But then what happens if a task takes too long to complete? Will all the other tasks be halted as we wait for this particular task to complete? This could clearly slow down our applications. To avoid such implications, javascript has a concurrency model based on the &lt;strong&gt;event loop&lt;/strong&gt; that provides it with the ability to process multiple tasks &lt;strong&gt;asynchronously&lt;/strong&gt;. &lt;br&gt;
This article will help you understand why javascript is single-threaded and yet asynchronous by learning about the javascript &lt;strong&gt;runtime environment&lt;/strong&gt;, the &lt;strong&gt;event loop&lt;/strong&gt; and the mechanisms behind it.&lt;/p&gt;
&lt;h2&gt;
  
  
  Javascript Runtime
&lt;/h2&gt;

&lt;p&gt;Each browser has a Javascript runtime environment.&lt;br&gt;
Here is an illustration to help us visualize the runtime.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5ud7sozw14rxvk6wh1kl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5ud7sozw14rxvk6wh1kl.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;br&gt;
So, the javascript runtime consists of&lt;/p&gt;
&lt;h3&gt;
  
  
  Javascript Engine
&lt;/h3&gt;

&lt;p&gt;Each browser uses its different version of the javascript engine. Some of the popular ones are V8(Chrome), Quantum(Firefox) and Webkit(Safari). Inside the engine, we have a memory heap and a call stack.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Memory heap&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Memory is allocated every time we create objects, declare functions or assign variables. This memory is stored in the heap.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Call Stack&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The single-threaded nature of javascript is because it has only one call stack. Within the call stack, your javascript code is read and executed line by line. The call stack follows the First In Last Out (FILO) principle, the function that is first added is executed last. once a function gets executed it's then get popped off the stack. Let's look at some code to clear the concept.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;getMovie&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Avengers&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="nf"&gt;getMovie&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="c1"&gt;// Avengers&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is how the JS engine handles this code...&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;first, it parses the code to check for syntax errors and once it finds none, it goes on to execute the code.&lt;/li&gt;
&lt;li&gt;it sees the getMovie() call and it pushes it to the stack.
&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft8lwtxtwv1eulc6xnwtt.png" alt="Alt Text"&gt;
&lt;/li&gt;
&lt;li&gt;getMovie() calls console.log() which then gets pushed to the top of the stack...
&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5tcglsri9pw1f9t2y8k9.png" alt="Alt Text"&gt;
&lt;/li&gt;
&lt;li&gt;JS engine executes that function and returns &lt;em&gt;Avengers&lt;/em&gt; to the console. The log is then popped off the stack.
&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe5m9pxz2c4r3ridqbg7x.png" alt="Alt Text"&gt;
&lt;/li&gt;
&lt;li&gt;The javascript engine then moves back to the getMovie() function, gets to its closing brackets and pops it off the stack(as it's done executing).
&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fagyc07hvold1d9kmamx7.png" alt="Alt Text"&gt;
As illustrated, the functions are added to the stack, executed and later deleted. Note that the function at the top of the stack is the one on focus and the JS engine only moves to the next frame(each entry in the call stack is called a stack frame) when the one above is returned and popped off the stack. This process of the call stack returning the frame at the top first before moving on to the next is why we say the JS engine runs &lt;strong&gt;synchronously.&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now suppose you want to fetch some data from an external file or you want to call an API that takes a while before it returns, You want the users to be able to continue using the program while waiting for the response, you cannot afford for your code to stop executing, javascript has a way to make this possible and here is where we introduce the &lt;strong&gt;Web APIs.&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Web APIs
&lt;/h3&gt;

&lt;p&gt;The Web APIs are provided by the browser, they live inside the browser's javascript runtime environment but outside the javascript engine. HTTP, AJAX, Geolocation, DOM events and setTimeout are all examples of the web APIs. Let's use a code example to help us figure out how web APIs help us in writing asynchronous code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;1&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// outputs 1 in the console&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;getNumber&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="c1"&gt;//in this setTimeout, we set the timer to 1s (1000ms = 1s)&lt;/span&gt;
&lt;span class="c1"&gt;//and pass a callback that returns after 1s&lt;/span&gt;
&lt;span class="nf"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;cb&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;2&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="nf"&gt;getNumber&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;3&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;//1&lt;/span&gt;
&lt;span class="c1"&gt;//3&lt;/span&gt;
&lt;span class="c1"&gt;//2&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's evaluate how javascript runs this code and its output&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;as usual, first, it parses the code looking for syntax errors and on finding none, it continues to execute the code.&lt;/li&gt;
&lt;li&gt;the first console.log is pushed to the stack, &lt;strong&gt;1&lt;/strong&gt; is returned and its popped off the stack.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;the next function, getNumber(), is pushed to the stack&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;getNumber() calls the setTimeout which is part of the web APIs, remember?&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg0adhx9x6ozzq9hk0e4s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg0adhx9x6ozzq9hk0e4s.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When the setTimeout is called to the stack, the callback with the timer is added to the appropriate web API where the countdown starts. The setTimeout is popped out of the stack.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;getNumber() is done returning and consequently removed from the stack.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;the last console.log is added to the stack, returns &lt;strong&gt;3&lt;/strong&gt; to the console, and removed from the stack.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvcoxbkl4pjzr2pzt6aj8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvcoxbkl4pjzr2pzt6aj8.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;br&gt;
So, what happens after 1s and the timer countdown is finished? You would think that the callback is popped back from the web API to the call stack, but if it did this, the callback would randomly appear in the middle of some other code being executed, to prevent such a scenario, web API adds the callback to the &lt;em&gt;message queue&lt;/em&gt; instead.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;strong&gt;message queue&lt;/strong&gt; is basically a data structure that javascript runtime uses to list messages that need to be processed. Unlike the call stack, the message queue uses the First In First Out(FIFO) principle, The first function added to the queue is processed first.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feie3hd6q6uqley6cvn5j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feie3hd6q6uqley6cvn5j.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;br&gt;
Now, how does javascript runtime know that the stack is empty? or how do events get pushed from the message queue to the call stack? enter the &lt;strong&gt;event loop.&lt;/strong&gt;&lt;br&gt;
The job of the &lt;strong&gt;event loop&lt;/strong&gt; is to constantly monitor the call stack and the message queue. If the call stack is empty, it takes the first event on the message queue and pushes it to the call stack. Both the call stack and the message queue may be empty for some time, but the event loop never stops checking.&lt;/p&gt;

&lt;p&gt;Back to our code, the event loop checks and sees that the call stack is empty, so it pushes our callback (cb) to the stack where it returns &lt;strong&gt;2&lt;/strong&gt; to the console and is then removed from the stack. Our code is done executing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In addition&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;What would happen if we passed 0 milliseconds to setTimeout?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;getCurrency&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="nf"&gt;setTimeout&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt;&lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;dollar&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="nf"&gt;getCurrency&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Frank&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="nf"&gt;name&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="c1"&gt;// Frank&lt;/span&gt;
&lt;span class="c1"&gt;// dollar&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you copy the above code and view it in the console, you shall notice that &lt;em&gt;Frank&lt;/em&gt; is printed first and then &lt;em&gt;dollar&lt;/em&gt;. Here is how JS handles this code:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;first, it parses the code looking for syntax errors before going on to execute it.&lt;/li&gt;
&lt;li&gt;getCurrency() is pushed to the stack.&lt;/li&gt;
&lt;li&gt;getCurrency() calls setTimeout, JS engine sees its a web API and thus adds it to the web APIs and setTimeout is popped off the stack. getCurrency() is also removed from the stack.&lt;/li&gt;
&lt;li&gt;Since the timer is set to 0s, web API immediately pushes the callback to the message queue, consequently, the event loop checks to see if the stack is empty, but it's not because&lt;/li&gt;
&lt;li&gt;as soon as setTimeout was removed from the stack, name() got pushed to the stack immediately.&lt;/li&gt;
&lt;li&gt;name() calls console.log which returns &lt;em&gt;Frank&lt;/em&gt; and pops off the stack.&lt;/li&gt;
&lt;li&gt;name() is done returning and is removed from the stack too.&lt;/li&gt;
&lt;li&gt;The event loop notices that the call stack is now empty and pushes the callback from the message queue to the call stack.&lt;/li&gt;
&lt;li&gt;The callback calls console.log, which returns &lt;em&gt;dollar&lt;/em&gt; and pops off the stack. The callback is done executing and is removed from the stack. Our code is finally done executing.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This code shows us that calling the setTimeout with a delay of 0 milliseconds doesn't execute the callback after the specified interval, the delay is the minimum time required by the runtime to execute the callback and not a guaranteed time.&lt;br&gt;
The callback has to wait for other queued messages to complete and the stack to clear before it's pushed to the stack and returned.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;Knowledge of the javascript runtime helps you understand how javascript runs under the hood and how different pieces fit together to make javascript the great language as we know it. I hope this article gave you a solid grasp of this fundamental concept. See yah!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>codenewbie</category>
    </item>
    <item>
      <title>How Memory Is Allocated In JavaScript.</title>
      <dc:creator>Kelvin Kirima</dc:creator>
      <pubDate>Thu, 28 Jan 2021 08:09:04 +0000</pubDate>
      <link>https://forem.com/kelvinkirima014/how-memory-is-allocated-in-javascript-1l65</link>
      <guid>https://forem.com/kelvinkirima014/how-memory-is-allocated-in-javascript-1l65</guid>
      <description>&lt;p&gt;When writing javascript code, you usually don't have to worry about memory management. This is because javascript automatically allocates the memory when we create variables,  objects and functions and releases the memory when they are not being used any more(the release of memory is known as garbage collection). Knowing how the memory is allocated is therefore not always necessary but it will help you gain more understanding of how javascript works and that is what you want, right?&lt;/p&gt;

&lt;h2&gt;
  
  
  Memory life cycle
&lt;/h2&gt;

&lt;p&gt;The memory life cycle is comprised of three steps, common across most programming languages. These steps are &lt;em&gt;memory allocation&lt;/em&gt;, &lt;em&gt;memory use&lt;/em&gt; and &lt;em&gt;memory release&lt;/em&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  memory allocation
&lt;/h2&gt;

&lt;p&gt;When you assign a variable, create an object or declare a function, some amount of memory has to be allocated.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// allocating memory via a variable&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;assignMemory&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;memory is assigned&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;

&lt;span class="c1"&gt;// allocating memory for an object and its values&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;myObject&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
 &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Kevin&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
 &lt;span class="na"&gt;title&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Frontend developer&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;//memory allocation for functions&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;getSum&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  memory use
&lt;/h2&gt;

&lt;p&gt;Memory is used every time we work with data in our code, either read or write. When we change the value of an object or pass an argument to a function, we are basically using memory, cool!&lt;/p&gt;

&lt;h2&gt;
  
  
  memory release
&lt;/h2&gt;

&lt;p&gt;When we no longer use the variables and objects, javascript automatically relieves this memory for us. It is, however, difficult to determine when the allocated memory is no longer needed. Javascript uses some form of memory management known as &lt;strong&gt;garbage collection&lt;/strong&gt; to monitor memory allocation and determine when allocated memory is no longer needed and release it. There is no method which can predict with complete accuracy which values are ready for release and as such the garbage collection process is mostly an approximation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Garbage Collection
&lt;/h2&gt;

&lt;p&gt;Since it's not possible to entirely decide which memory is needed or not, garbage collectors use two algorithms to evaluate which objects can be removed from memory. Let's look at these algorithms and their limitations.&lt;/p&gt;

&lt;h2&gt;
  
  
  Reference
&lt;/h2&gt;

&lt;p&gt;In the reference counting algorithm, an object is evaluated as garbage if no other part of the code reference to it. Let's look at this code in order to get this concept clearly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;//create an object in the global scope&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;toWatch&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;showName&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Big Bang Theory&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="c1"&gt;//javascript allocates memory for the showName object&lt;/span&gt;
&lt;span class="c1"&gt;// the toWatch variable becomes reference for this object&lt;/span&gt;
&lt;span class="c1"&gt;//this existing reference prevents showName from being&lt;/span&gt;
&lt;span class="c1"&gt;//being removed by the garbage collector&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The only existing reference to the showName object above is the toWatch variable. If you remove this variable, the garbage collector will know the object it pointed to is no longer needed and it will release it from the memory.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;toWatch&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;
&lt;span class="c1"&gt;//garbage collector will detect that&lt;/span&gt;
&lt;span class="c1"&gt;//the showName object is no longer reachable and&lt;/span&gt;
&lt;span class="c1"&gt;//not needed and it will release it from memory&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The major drawback of this algorithm is that it does not pick up on &lt;strong&gt;circular reference&lt;/strong&gt;. If two variables reference each other but are not needed on any other part of the code, the garbage collector will not remove them from memory as they are referenced and thus 'needed' as per the standards of this method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;//create a function that has a circular reference&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;circularRef&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
 &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;foo&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;
 &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;bar&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{}&lt;/span&gt;
 &lt;span class="nx"&gt;foo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;bar&lt;/span&gt;
 &lt;span class="nx"&gt;bar&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;foo&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="nx"&gt;circularRef&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="c1"&gt;//though variables foo and bar don't exist outside&lt;/span&gt;
&lt;span class="c1"&gt;//this function, garbage collector will not count &lt;/span&gt;
&lt;span class="c1"&gt;//them as ready for collection because they&lt;/span&gt;
&lt;span class="c1"&gt;//reference each other&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Mark and Sweep algorithm
&lt;/h2&gt;

&lt;p&gt;This algorithm views an object as ready for collection if it is not connected to the &lt;em&gt;root&lt;/em&gt;. In javascript, the root is the global object. The garbage collector visits all objects connected to the root(global object) and marks them as &lt;em&gt;reachable&lt;/em&gt; or &lt;em&gt;live&lt;/em&gt;. It then marks all objects that are connected to the &lt;em&gt;root&lt;/em&gt;. This approach solves the circular reference problem because all elements not connected to the global object will not be marked as &lt;em&gt;live&lt;/em&gt;, regardless of if it's referenced by other non-live elements.&lt;br&gt;
Those elements that are not marked are considered unreachable and safe for collection.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Memory allocation and garbage collection works automatically, as developers we do not have to trigger it or prevent it but I hope this article gave you a good grasp of the process and what happens on the background.&lt;/p&gt;

&lt;p&gt;p.s feel free to ask me any question regarding this(or anything javascript) or add a comment. Thanks, ciao!&lt;/p&gt;

</description>
      <category>codenewbie</category>
      <category>discuss</category>
      <category>javascript</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
