<?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: Nirmalya Sengupta</title>
    <description>The latest articles on Forem by Nirmalya Sengupta (@nsengupta).</description>
    <link>https://forem.com/nsengupta</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%2F18841%2Fea750975-f8a1-45e9-a070-96dc41d94e81.jpeg</url>
      <title>Forem: Nirmalya Sengupta</title>
      <link>https://forem.com/nsengupta</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/nsengupta"/>
    <language>en</language>
    <item>
      <title>Rust Notes on Temporary values (usage of Mutex) - 4</title>
      <dc:creator>Nirmalya Sengupta</dc:creator>
      <pubDate>Thu, 22 Jun 2023 11:56:48 +0000</pubDate>
      <link>https://forem.com/nsengupta/rust-notes-on-temporary-values-usage-of-mutex-4-498c</link>
      <guid>https://forem.com/nsengupta/rust-notes-on-temporary-values-usage-of-mutex-4-498c</guid>
      <description>&lt;h3&gt;
  
  
  Preface
&lt;/h3&gt;

&lt;p&gt;Some weeks back, in the discord &lt;strong&gt;LetsGoRusty&lt;/strong&gt; server, a topic of &lt;a href="https://discord.com/channels/818251276378701824/974963208278392832/1107995248459788328"&gt;discussion&lt;/a&gt; was the behavior of match expression vis-a-vis a lock. The thread of discussion was quite interesting for me. Fellow members of the channel exchanged messages, much to my benefit. After all, I am learning Rust! 😁 &lt;/p&gt;

&lt;p&gt;In short, the problem was 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;match&lt;/span&gt; &lt;span class="n"&gt;receiver&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.recv&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; 
    &lt;span class="c1"&gt;// ...&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and&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="c1"&gt;// ...&lt;/span&gt;
&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;receiver&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.recv&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="k"&gt;match&lt;/span&gt; &lt;span class="n"&gt;message&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// ....&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;behave differently, Why?&lt;/p&gt;

&lt;p&gt;As someone who is learning Rust enthusiastically, and fighting the Borrow Checker valiantly along the way 😃 this question intrigued me. I wanted to find out - to the extent I could - the exact reason behind this behaviour. Whatever I have been able to understand, I have captured in a series of articles (listed below). This is the &lt;strong&gt;last and final&lt;/strong&gt; article of that series.&lt;/p&gt;

&lt;h3&gt;
  
  
  Build up
&lt;/h3&gt;

&lt;p&gt;Perhaps, it will be easier to understand the background of this article, if the ones just preceding it (in order as below) are referred to:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Explores Method-call expressions and binding. (&lt;a href="https://dev.to/nsengupta/rust-notes-on-temporary-values-in-method-call-expressions-1-1g8"&gt;link&lt;/a&gt;)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Explores RAII, OBMR and how these are used in establishing the behaviour of a Mutex (&lt;a href="https://dev.to/nsengupta/rust-notes-on-temporary-values-usage-of-mutex-2-403p"&gt;link&lt;/a&gt;)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Explores the interplay between the scope of a temporary and &lt;em&gt;match&lt;/em&gt; expressions - 3 (&lt;a href="https://dev.to/nsengupta/rust-notes-on-temporary-values-scope-of-mutexguard-and-match-expressions-3-4c85"&gt;link&lt;/a&gt;) &lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  What are the main takeaways so far (summary of the earlier articles)
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  An expression like &lt;code&gt;a.b().c()&lt;/code&gt; is called a Method-call expression. It is kind of obvious that &lt;code&gt;c()&lt;/code&gt; can be called only when a &lt;em&gt;receiver&lt;/em&gt; object exists which implements the method &lt;code&gt;c()&lt;/code&gt;. A method/function cannot be called in isolation. The question is, which is the receiver object in that expression, on which &lt;code&gt;c()&lt;/code&gt; is available.&lt;/li&gt;
&lt;li&gt;  Any expression evaluates to a value. So, does a Method-call expression, as well. How we deal with that value is important.&lt;/li&gt;
&lt;li&gt;  In order to facilitate execution of a Method-call expression, #rustlang compiler brings forth &lt;strong&gt;temporary&lt;/strong&gt; objects as receivers of the methods. The scope - i.e. how long is it available - of these temporaries are governed by a few rules. &lt;/li&gt;
&lt;li&gt;  The purpose of having a Mutex is to set up a fence around a piece of data. When a thread of execution needs an access to this piece of data, the Mutex must set up a lock around the data, ensuring an exclusive access by this particular thread. While the lock is in place, no other thread can access the data. Therefore, it is important to remove the exclusive lock, just when the current thread of execution is done with it.&lt;/li&gt;
&lt;li&gt;  Rust employs a technique named OBMR (more commonly known as RAII) to implement the lock by creating temporary object of type &lt;code&gt;MutexGuard&lt;/code&gt; and using the scoping rules to ensure its timely destruction (thereby, releasing the lock).&lt;/li&gt;
&lt;li&gt;  When used in a &lt;code&gt;match&lt;/code&gt; expression, the rules of scoping the temporaries determine how the lock is held and released. This is an important observation.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  A brief description of the application where it started
&lt;/h3&gt;

&lt;p&gt;The Discord discussion &lt;a href="https://discord.com/channels/818251276378701824/974963208278392832/1107995248459788328"&gt;thread&lt;/a&gt;, is about a multi-threaded webserver toy application, from the the Rust &lt;a href="https://doc.rust-lang.org/book/ch20-02-multithreaded.html"&gt;Book&lt;/a&gt;. This application demonstrates - amongst other things - inter-thread communication using &lt;a href="https://doc.rust-lang.org/std/sync/mpsc/fn.channel.html"&gt;Channels&lt;/a&gt;. A bunch of workers is looking for jobs to arrive at a channel: when a job arrives, a worker picks it up and executes. This article is not about threads and channels; so we don't go that way. It is sufficient for us to know that the &lt;code&gt;Channel&lt;/code&gt; (the receiving end of the channel, to be accurate but that is not important) is held inside a Mutex. Any thread that needs to peep in the channel to see if a job is waiting to be picked up, must &lt;strong&gt;acquire the lock&lt;/strong&gt;! &lt;/p&gt;

&lt;h3&gt;
  
  
  What is the real issue with the behaviour here?
&lt;/h3&gt;

&lt;p&gt;Well, imagine a queue of jobs. One thread acquires the lock on the queue and picks up a job which is at the mouth of the queue. Once it picks up, it is going to execute the job. During the execution, it must release the lock, so that the next job at the mouth of the queue, may be picked up by another thread. Nothing really very complicated, so far. &lt;/p&gt;

&lt;p&gt;But, what if the first thread never releases the lock? In that case, even if jobs accumulate in the queue, other threads - even if free - will remain idle. The first thread, when it is done with the current job, will get a chance to peek again and extract the next job. Only this thread will be working, and in effect, the application will behave as if it is single-threaded.&lt;/p&gt;

&lt;h3&gt;
  
  
  Explaining the behavior
&lt;/h3&gt;

&lt;p&gt;The code snippet that began the &lt;a href="https://discord.com/channels/818251276378701824/974963208278392832/1107995248459788328"&gt;discussion&lt;/a&gt; on 'Let's Go Rusty' Discord server, was:&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="c1"&gt;// ...&lt;/span&gt;
&lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;receiver&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.recv&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;  
&lt;span class="k"&gt;match&lt;/span&gt; &lt;span class="n"&gt;message&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;                                &lt;span class="c1"&gt;// &amp;lt;-- match on the bound variable&lt;/span&gt;
    &lt;span class="nn"&gt;Message&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;NewJob&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;job&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="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Worker {} got a new job, executing .."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nf"&gt;job&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="nn"&gt;Message&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Terminate&lt;/span&gt; &lt;span class="k"&gt;=&amp;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;"Worker {} was told to terminate!"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;id&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="p"&gt;}&lt;/span&gt;
&lt;span class="c1"&gt;// ...&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The point was that the behaviour was different (as outlined earlier) when the first line in the snippet is chaged to 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="c1"&gt;// ...&lt;/span&gt;
&lt;span class="k"&gt;match&lt;/span&gt; &lt;span class="n"&gt;receiver&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.recv&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;  &lt;span class="c1"&gt;// &amp;lt;-- match on the expression&lt;/span&gt;
    &lt;span class="nn"&gt;Message&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;NewJob&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;job&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="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Worker {} got a new job, executing .."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="nf"&gt;job&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="nn"&gt;Message&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Terminate&lt;/span&gt; &lt;span class="k"&gt;=&amp;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;"Worker {} was told to terminate!"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;id&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="p"&gt;}&lt;/span&gt;
&lt;span class="c1"&gt;// ...&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the second case, the lock is held till the end of the &lt;code&gt;match&lt;/code&gt; expression as we have seen in the earlier article. Therefore, while the &lt;code&gt;job()&lt;/code&gt; is being done, receiver's channel - the job-queue's head - is locked (the &lt;code&gt;MutexGuard&lt;/code&gt; is alive). No other thread can access the receiver's channel during this time. In effect, the application behaves as if it is single threaded.&lt;/p&gt;

&lt;h3&gt;
  
  
  Expressions &lt;code&gt;while let&lt;/code&gt;  and  &lt;code&gt;match&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;The example shared on Discord is &lt;em&gt;almost&lt;/em&gt; the same as the sample multi-threaded application that is &lt;a href="https://doc.rust-lang.org/book/ch20-02-multithreaded.html"&gt;implemented&lt;/a&gt; in the Rust book. The book, also mentions the same problem as described above, but as a slightly different case. &lt;/p&gt;

&lt;p&gt;This works as a multi-threaded server alright:&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="c1"&gt;// --snip--&lt;/span&gt;

&lt;span class="k"&gt;impl&lt;/span&gt; &lt;span class="n"&gt;Worker&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;new&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;usize&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;receiver&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Arc&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Mutex&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nn"&gt;mpsc&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Receiver&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Job&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;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="n"&gt;Worker&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;thread&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;thread&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;spawn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;move&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="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;job&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;receiver&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.recv&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// &amp;lt;==  the lock is released here (tempprary dropped)&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;"Worker {id} got a job; executing."&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="nf"&gt;job&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;  &lt;span class="c1"&gt;// &amp;lt;-- do the job and then loop back again&lt;/span&gt;
        &lt;span class="p"&gt;});&lt;/span&gt;

        &lt;span class="n"&gt;Worker&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;thread&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;But, this behaves as a single-threaded server:&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="c1"&gt;// --snip--&lt;/span&gt;

&lt;span class="k"&gt;impl&lt;/span&gt; &lt;span class="n"&gt;Worker&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;new&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;usize&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;receiver&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Arc&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Mutex&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nn"&gt;mpsc&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Receiver&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Job&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&amp;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="n"&gt;Worker&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;thread&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;thread&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;spawn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;move&lt;/span&gt; &lt;span class="p"&gt;||&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nf"&gt;Ok&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;job&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;receiver&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.recv&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="c1"&gt;// &amp;lt;-- lock is not released ...&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;"Worker {id} got a job; executing."&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
                &lt;span class="nf"&gt;job&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;                                                     &lt;span class="c1"&gt;// &amp;lt;-- till here!&lt;/span&gt;
        &lt;span class="p"&gt;});&lt;/span&gt;

        &lt;span class="n"&gt;Worker&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;thread&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;There is no &lt;code&gt;match&lt;/code&gt; yet the behaviour is the same as in &lt;code&gt;match receiver.lock().unwrap().recv()&lt;/code&gt;. Why?&lt;/p&gt;

&lt;p&gt;This is so because Rust compiler translates a &lt;code&gt;while let() = .....&lt;/code&gt; into a &lt;code&gt;match&lt;/code&gt; expression! &lt;/p&gt;

&lt;p&gt;The &lt;code&gt;while let Ok(Job) = receiver.lock().unwrap().recv()&lt;/code&gt; is made into something equivalent to 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;loop&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;match&lt;/span&gt; &lt;span class="n"&gt;receiver&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.recv&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;  &lt;span class="c1"&gt;// &amp;lt;-- lock is not released&lt;/span&gt;
            &lt;span class="nf"&gt;Ok&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;job&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;job&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="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="p"&gt;}&lt;/span&gt;                                        &lt;span class="c1"&gt;// &amp;lt;-- till here!&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Like earlier, the lock is still held inside the &lt;code&gt;match&lt;/code&gt; arm and is not released till the end of the expression, and then it loops!&lt;/p&gt;

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

&lt;p&gt;An idiomatic use of &lt;code&gt;Mutex&lt;/code&gt; requires us to understand the important role that a temporary &lt;code&gt;MutexGuard&lt;/code&gt; plays of fencing and freeing the data that is under &lt;code&gt;Mutex&lt;/code&gt; 's lock. The `&lt;code&gt;MutexGuard&lt;/code&gt; 's construction and destruction ensure that the lock is held and released at the appropriate time, so that access to data is not prevented when it is necessary. The rules that govern the scope of a temporary in a Rust expression, is crucial here because the rules ensure how long the &lt;code&gt;MutexGuard&lt;/code&gt; lives!&lt;/p&gt;




&lt;p&gt;It will be fantastic to hear your comments, on this series. If this benefits someone, I will be happy. I will be happier if &lt;strong&gt;someone spots and points out the gaps&lt;/strong&gt; in my understanding. I am learning and any help is welcome! 😃.&lt;/p&gt;

</description>
      <category>rust</category>
      <category>mutex</category>
    </item>
    <item>
      <title>Rust Notes on Temporary values (usage of Mutex) - 3</title>
      <dc:creator>Nirmalya Sengupta</dc:creator>
      <pubDate>Wed, 21 Jun 2023 06:50:31 +0000</pubDate>
      <link>https://forem.com/nsengupta/rust-notes-on-temporary-values-scope-of-mutexguard-and-match-expressions-3-4c85</link>
      <guid>https://forem.com/nsengupta/rust-notes-on-temporary-values-scope-of-mutexguard-and-match-expressions-3-4c85</guid>
      <description>&lt;p&gt;[Cover image credit: &lt;a href="https://pixabay.com/users/engin_akyurt-3656355"&gt;https://pixabay.com/users/engin_akyurt-3656355&lt;/a&gt;]&lt;/p&gt;

&lt;h3&gt;
  
  
  Build up
&lt;/h3&gt;

&lt;p&gt;Perhaps, it will be easier to understand the background of this article, if the ones just preceding it (in the series) are referred to:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Rust Notes on Temporary values (usage of Mutex) - 1  (&lt;a href="https://dev.to/nsengupta/rust-notes-on-temporary-values-in-method-call-expressions-1-1g8"&gt;link&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;Explores Method-call expressions and binding.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Rust Notes on Temporary values (usage of Mutex) - 2 (&lt;a href="https://dev.to/nsengupta/rust-notes-on-temporary-values-usage-of-mutex-2-403p"&gt;link&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;Explores RAII, OBMR and how these are used in establishing the behaviour of a Mutex&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Mutex is used to fence a piece of data. Any access to this data, is preceded by acquiring a lock on it. Releasing this lock is crucial, because unless that happens, subsequent access to this data will be impossible. In the preceding article, we have briefly seen how a combination of RAII (or OBMR) and Scoping rules of Rust, makes this very straightforward. However, are there cases where the lock is held for longer than we expect?&lt;/p&gt;

&lt;h3&gt;
  
  
  Revisiting accessing the fenced data
&lt;/h3&gt;

&lt;p&gt;We have seen this snippet 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;use&lt;/span&gt; &lt;span class="nn"&gt;std&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;sync&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Mutex&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="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Mutex&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="mi"&gt;5&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;stringified&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.to_string&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// multiple transformations here!    &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;"stringified -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;stringified&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;"Mutex itself -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a_mutex&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;"Good bye!"&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;&lt;code&gt;a_mutex.lock().unwrap().to_string()&lt;/code&gt;: In that expression, multiple steps are taking place:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Lock is obtained from &lt;code&gt;a_mutex&lt;/code&gt;. An unnamed &lt;code&gt;MutexGuard&lt;/code&gt; object is produced.&lt;/li&gt;
&lt;li&gt;  The &lt;code&gt;MutexGuard&lt;/code&gt; is unwrapped and its internal &lt;code&gt;i32&lt;/code&gt; ( value of '5') is made available (through a mechanism of &lt;em&gt;deref&lt;/em&gt; but that is not important here)&lt;/li&gt;
&lt;li&gt;  The &lt;code&gt;to_string()&lt;/code&gt; method available on &lt;code&gt;i32&lt;/code&gt; is called.&lt;/li&gt;
&lt;li&gt;  A stringified representation of numeric '5' is produced. This is the final value of the expression.&lt;/li&gt;
&lt;li&gt;  Then the expression is complete and the statement ends. Unnamed &lt;code&gt;MutexGuard&lt;/code&gt; goes out of scope and hence, dropped. The lock is released.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This stringified representation is assigned to (bound to) &lt;code&gt;stringified&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Importantly, just before that &lt;strong&gt;;&lt;/strong&gt;, the scope of unnamed &lt;code&gt;MutexGuard&lt;/code&gt; ends, and it is dropped, thereby releasing the lock. That is as well, because once we call &lt;code&gt;to_string()&lt;/code&gt;, our objective has been fulfilled.&lt;/p&gt;

&lt;h3&gt;
  
  
  Can we force the guard to stay open for longer?
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;MutexGuard&lt;/code&gt; is dropped when the statement ends. What if we want the guard to exist, till we want? &lt;/p&gt;

&lt;p&gt;We have already seen 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;use&lt;/span&gt; &lt;span class="nn"&gt;std&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;sync&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Mutex&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="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Mutex&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="mi"&gt;5&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;guard&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// &amp;lt;-- 'guard' is of type `MutexGuard`&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;"guard -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;guard&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;"Mutex itself -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="c1"&gt;// An attempt to acquire the lock again.&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="nf"&gt;.try_lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&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;"Good bye!"&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 output clearly shows that the mutex is in a locked state and an attempt to acquire the lock again is disallowed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;guard -&amp;gt; 5
Mutex itself -&amp;gt; Mutex &lt;span class="o"&gt;{&lt;/span&gt; data: &amp;lt;locked&amp;gt;, poisoned: &lt;span class="nb"&gt;false&lt;/span&gt;, .. &lt;span class="o"&gt;}&lt;/span&gt;
thread &lt;span class="s1"&gt;'main'&lt;/span&gt; panicked at &lt;span class="s1"&gt;'called `Result::unwrap()` on an `Err` value: "WouldBlock"'&lt;/span&gt;, src/main.rs:37:32
note: run with &lt;span class="sb"&gt;`&lt;/span&gt;&lt;span class="nv"&gt;RUST_BACKTRACE&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;1&lt;span class="sb"&gt;`&lt;/span&gt; environment variable to display a backtrace
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Why? Because the &lt;code&gt;MutexGuard&lt;/code&gt; has not gone out of scope. It is now bound to a variable &lt;code&gt;guard&lt;/code&gt;; therefore it is not temporary anymore. In fact the &lt;code&gt;MutexGuard&lt;/code&gt;'s scope now spans till the end of the block, i.e. end of &lt;code&gt;main&lt;/code&gt; in this case.&lt;/p&gt;

&lt;p&gt;Clearly, the scope of &lt;code&gt;MutexGuard&lt;/code&gt; ends when we operate directly on it by calling a method on value it is &lt;em&gt;guarding&lt;/em&gt; but not when we bind it to a variable, and then operate on it. Does any other case exist, where the scope is extended?&lt;/p&gt;

&lt;h3&gt;
  
  
  Making use of &lt;code&gt;match&lt;/code&gt; expression
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;lock()&lt;/code&gt; returns a &lt;code&gt;LockResult&lt;/code&gt;; therefore, we can &lt;em&gt;match&lt;/em&gt; on it:&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;use&lt;/span&gt; &lt;span class="nn"&gt;std&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;sync&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Mutex&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="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Mutex&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="mi"&gt;5&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;stringified&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;match&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="c1"&gt;// &amp;lt;--- scope begins&lt;/span&gt;

        &lt;span class="nf"&gt;Ok&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;guard&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="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;guard&lt;/span&gt;&lt;span class="nf"&gt;.to_string&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;"Mutex itself on a match arm -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="n"&gt;v&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;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nd"&gt;panic!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"We don't expect it here {}!"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="nf"&gt;.get_ref&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt; &lt;span class="c1"&gt;// 'e' carries the guard inside it&lt;/span&gt;
    &lt;span class="p"&gt;};&lt;/span&gt; &lt;span class="c1"&gt;// &amp;lt;-- scope ends&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;"stringified -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;stringified&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;"Mutex itself after guard is released -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a_mutex&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;"Good bye!"&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 output confirms that the lock is released, but after the entire &lt;em&gt;match&lt;/em&gt; expression, ends:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;Mutex itself &lt;span class="k"&gt;while &lt;/span&gt;guard is alive, on a match arm -&amp;gt; Mutex &lt;span class="o"&gt;{&lt;/span&gt; data: &amp;lt;locked&amp;gt;, poisoned: &lt;span class="nb"&gt;false&lt;/span&gt;, .. &lt;span class="o"&gt;}&lt;/span&gt;
stringified -&amp;gt; &lt;span class="s2"&gt;"5"&lt;/span&gt;
Mutex itself after guard is released -&amp;gt; Mutex &lt;span class="o"&gt;{&lt;/span&gt; data: 5, poisoned: &lt;span class="nb"&gt;false&lt;/span&gt;, .. &lt;span class="o"&gt;}&lt;/span&gt;
Good bye!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, the temporary here is being held inside the arm. Let us go a bit further.&lt;/p&gt;

&lt;p&gt;In this case:&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;use&lt;/span&gt; &lt;span class="nn"&gt;std&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;sync&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Mutex&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="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Mutex&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="mi"&gt;5&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;stringified&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.to_string&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// &amp;lt;-- MutexGuard's scope ends heres&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;"stringified -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;stringified&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;"Mutex itself after guard is released -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a_mutex&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;"Good bye!"&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 lock is released at the end of the statement ( conceptually, when &lt;strong&gt;;&lt;/strong&gt; is reached ).&lt;/p&gt;

&lt;p&gt;But, not in this case:&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;use&lt;/span&gt; &lt;span class="nn"&gt;std&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;sync&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Mutex&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="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Mutex&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="mi"&gt;5&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;stringified&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;match&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.to_string&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.as_str&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="s"&gt;"5"&lt;/span&gt; &lt;span class="k"&gt;=&amp;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;"We have received a five!"&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;"Mutex itself while guard is alive, on a match arm -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="nf"&gt;.to_owned&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="k"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s"&gt;"Not a five"&lt;/span&gt;&lt;span class="nf"&gt;.to_owned&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;};&lt;/span&gt;  &lt;span class="c1"&gt;// &amp;lt;-- lock is released here!&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;"stringified -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;stringified&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;"Mutex itself after guard is released -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a_mutex&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;&lt;strong&gt;Note&lt;/strong&gt;: That &lt;code&gt;.as_str()&lt;/code&gt; is required for idiomatically *match*ing String literals. It has got nothing to do with the core discussion here. The basic point remains the same: how long is the lock being acquired and held?&lt;/p&gt;




&lt;p&gt;The scoping rules come into play. The expression that follows a &lt;code&gt;match&lt;/code&gt; is called a &lt;strong&gt;&lt;a href="https://rustwiki.org/en/reference/glossary.html#scrutinee"&gt;Scrutinee Expression&lt;/a&gt;&lt;/strong&gt;. In case a scrutinee expression generates a temporary value (viz., &lt;code&gt;MutexGuard&lt;/code&gt;) it is not dropped till the end of scope of &lt;code&gt;match&lt;/code&gt; expression. As a consequence, the lock is held, till the &lt;code&gt;match&lt;/code&gt; expression comes to an end.&lt;/p&gt;

&lt;p&gt;This has implications which may not be obvious. For example, what happens in this case?&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;use&lt;/span&gt; &lt;span class="nn"&gt;std&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;sync&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Mutex&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="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Mutex&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="mi"&gt;5&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;stringified&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;match&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.to_string&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.as_str&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="s"&gt;"5"&lt;/span&gt; &lt;span class="k"&gt;=&amp;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;"Mutex itself while guard is alive, on a match arm -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="c1"&gt;// the lock is held here..&lt;/span&gt;
            &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;do_some_long_calculation&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// Example function, not implemented&lt;/span&gt;
            &lt;span class="c1"&gt;// the lock is still held here..&lt;/span&gt;
            &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;q&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;make_a_network_call&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;    &lt;span class="c1"&gt;// Example function, not implemented&lt;/span&gt;
            &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="nf"&gt;.to_owned&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;q&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="k"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s"&gt;"Not a five"&lt;/span&gt;&lt;span class="nf"&gt;.to_owned&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;};&lt;/span&gt;  &lt;span class="c1"&gt;// &amp;lt;-- lock is released here!&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;"stringified -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;stringified&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;"Mutex itself after guard is released -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a_mutex&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;Executing functions, which take time to finish, will effectively prevent the lock from being released. If someone else is waiting for the lock (may be, another thread), tough luck!&lt;/p&gt;

&lt;p&gt;Before we close, let's contrast the code above, with the code below:&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;use&lt;/span&gt; &lt;span class="nn"&gt;std&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;sync&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Mutex&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="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Mutex&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="mi"&gt;5&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;unfenced&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.to_string&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// &amp;lt;-- MutexGuard goes out of scope&lt;/span&gt;

    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;stringified&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;match&lt;/span&gt; &lt;span class="n"&gt;unfenced&lt;/span&gt;&lt;span class="nf"&gt;.as_str&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="c1"&gt;// like earlier, ignore the as_str() function&lt;/span&gt;

        &lt;span class="n"&gt;s&lt;/span&gt; &lt;span class="o"&gt;@&lt;/span&gt; &lt;span class="s"&gt;"5"&lt;/span&gt; &lt;span class="k"&gt;=&amp;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;"We have received a five!"&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;"Mutex itself while guard is alive, on a match arm -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="nf"&gt;.to_owned&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="k"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s"&gt;"Not a five"&lt;/span&gt;&lt;span class="nf"&gt;.to_owned&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;"stringified -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;stringified&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;"Mutex itself after guard is released -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a_mutex&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;"Good bye!"&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;h3&gt;
  
  
  Main Takeaways
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  In order to extend a temporary value's scope, it is bound to a variable using the &lt;code&gt;let&lt;/code&gt; statement.&lt;/li&gt;
&lt;li&gt;  In case of &lt;code&gt;MutexGuard&lt;/code&gt;, a &lt;code&gt;let&lt;/code&gt; statement forces the guard to exist for longer (depends on the scope of the &lt;code&gt;let&lt;/code&gt; variable). While the guard exists, the lock on the innter piece of data remains acquired. &lt;/li&gt;
&lt;li&gt;  In case using &lt;code&gt;match&lt;/code&gt; expression that works on a temporary, the scope extends till the end of the &lt;code&gt;match&lt;/code&gt; expression.&lt;/li&gt;
&lt;li&gt;  Because an arm of a &lt;code&gt;match&lt;/code&gt; can execute arbitrary logic, the lock can be held for longer than expected or even, necessary. This is an important observation.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Acknowledgements
&lt;/h2&gt;

&lt;p&gt;In my quest to understand the behaviour of the compiler in this case, I have gone through a number of articles / blogs / explanations. I will be unfair and utterly discourteous on my part, if I don't mention the some of them. This blog stands on the shoulders of those authors and elaborators:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;My specific question on stackoverflow and fantastic answers given by &lt;a href="https://stackoverflow.com/users/7884305/chayim-friedman"&gt;Chayim Friedman&lt;/a&gt;, &lt;a href="https://stackoverflow.com/users/8182118/masklinn"&gt;masklinn&lt;/a&gt;, and &lt;a href="https://stackoverflow.com/users/5209502/paul"&gt;paul&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;This &lt;a href="https://stackoverflow.com/questions/71170147/temporary-value-dropped-while-borrowed"&gt;stackoverflow&lt;/a&gt; QnA On, how the lock should be treated, in order to make use of the value tucked inside the mutex. &lt;/li&gt;
&lt;li&gt;This &lt;a href="[https://](https://stackoverflow.com/questions/51335679/where-is-a-mutexguard-if-i-never-assign-it-to-a-variable)"&gt;post&lt;/a&gt; has been extremely valuable for me to understand the issue of interplay between &lt;strong&gt;Place Context&lt;/strong&gt; and &lt;strong&gt;Value Context&lt;/strong&gt;! Thank you &lt;a href="https://stackoverflow.com/users/2408867/lukas-kalbertodt"&gt;Lukas Kalberbolt&lt;/a&gt;. A great question is posed by &lt;a href="https://stackoverflow.com/users/498680/animatedrng"&gt;AnimatedRNG&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>rust</category>
      <category>mutex</category>
      <category>scope</category>
    </item>
    <item>
      <title>Rust Notes on Temporary values (usage of Mutex) - 2</title>
      <dc:creator>Nirmalya Sengupta</dc:creator>
      <pubDate>Fri, 16 Jun 2023 04:26:57 +0000</pubDate>
      <link>https://forem.com/nsengupta/rust-notes-on-temporary-values-usage-of-mutex-2-403p</link>
      <guid>https://forem.com/nsengupta/rust-notes-on-temporary-values-usage-of-mutex-2-403p</guid>
      <description>&lt;p&gt;[Cover image credit: &lt;a href="https://pixabay.com/users/engin_akyurt-3656355"&gt;https://pixabay.com/users/engin_akyurt-3656355&lt;/a&gt;]&lt;/p&gt;

&lt;h3&gt;
  
  
  Build up
&lt;/h3&gt;

&lt;p&gt;In &lt;a href="https://dev.to/nsengupta/rust-notes-on-temporary-values-in-method-call-expressions-1-1g8"&gt;this&lt;/a&gt; article (first in the series), I have elaborated the understanding of temporary objects / variables in an expression, their scopes and behaviour.&lt;/p&gt;

&lt;p&gt;This article is a continuation of the same topic, but it explores a much-used (and very crucial in multi-threaded context) type in Rust programming:  the &lt;code&gt;Mutex&lt;/code&gt; .&lt;/p&gt;

&lt;h3&gt;
  
  
  Quick definition for the context
&lt;/h3&gt;

&lt;p&gt;The concept of a Mutex (&lt;strong&gt;Mut&lt;/strong&gt;ual &lt;strong&gt;Ex&lt;/strong&gt;clusion) is ages old. The idea is to ensure that only one thread of execution can access and modify a piece of data in memory, it must be locked first and unlocked, post-modification. All threads must govern themselves by checking for the lock's availabilty before going ahead with the modification; if the lock is not avaiable (meaning, some other thread is in the middle of modifying the data beind the lock), it must not gatecrash but wait, patiently.The Rust bool's chapter on &lt;a href="https://doc.rust-lang.org/book/ch16-03-shared-state.html?highlight=mutex#using-mutexes-to-allow-access-to-data-from-one-thread-at-a-time"&gt;Mutex&lt;/a&gt; is a recommended read.&lt;/p&gt;

&lt;h3&gt;
  
  
  Mutex in Rust
&lt;/h3&gt;

&lt;p&gt;The crucial and tricky thing about a Mutex is about when to put in the lock around the inner data (rememember: a lock's existence is jutsified because it is &lt;em&gt;guarding&lt;/em&gt; some piece of data in memory) and when to lift it. The sequecnce of &lt;em&gt;acquiring&lt;/em&gt; and &lt;em&gt;releasing&lt;/em&gt; the lock extremely important. Before we try to understand the way it is done in Rust, we should get familiarized with a term: RAII.&lt;/p&gt;

&lt;h4&gt;
  
  
  RAII
&lt;/h4&gt;

&lt;p&gt;RAII stands for, rather too predictably, &lt;strong&gt;R&lt;/strong&gt;esource &lt;strong&gt;A&lt;/strong&gt;cquisition &lt;strong&gt;I&lt;/strong&gt;s &lt;strong&gt;I&lt;/strong&gt;nitialization (phew!). C++ experts are quite familiar with it. I will not delve deep into this topic - other detailed descriptions like &lt;a href="https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization"&gt;this&lt;/a&gt;, &lt;a href="https://learn.microsoft.com/en-us/cpp/cpp/object-lifetime-and-resource-management-modern-cpp?view=msvc-170"&gt;this&lt;/a&gt; and &lt;a href="https://www.youtube.com/watch?v=uT3wL9K0DoQ"&gt;this&lt;/a&gt; and several others - exist for a deeper understanding. &lt;/p&gt;

&lt;p&gt;Put very simply, RAII is a mechanism which stipulates that any access to a computing resource (viz., memory,file, DB Connection etc.) must be preceded by its construction. While this sounds kind of given, the subsequent part is what is important: the access to resource is denied after the destruction of the resource. In other words, the resource is available strictly between its creation and demise.The duration between these two stages of life, is determined by the scoping rules.&lt;/p&gt;

&lt;h4&gt;
  
  
  OBRM
&lt;/h4&gt;

&lt;p&gt;I have come across this term while tinkering with Rust. OBRM stands for &lt;em&gt;O*wnership *B*ased *R*esource *M*anagament (you don't like the acronym? I don't, either 😃 ). Again, I will not delve into this either (I find these 2 good videos by #letsgorusty &lt;a href="https://www.youtube.com/watch?v=AnFaf-L_DfE"&gt;here&lt;/a&gt; and &lt;a href="https://www.youtube.com/watch?v=7EcNkr6KFy0"&gt;here&lt;/a&gt;, quite explanatory). The main understanding is this: acquisition and release of resources are governed by the *Ownership&lt;/em&gt; rules of Rust. Put simply, when the object (say, a constructed &lt;code&gt;struct&lt;/code&gt;) that holds the resource is destroyed ( *Drop*ped ), the resource is released too. Automatically! The language ensures this behavior!&lt;/p&gt;

&lt;p&gt;My objective is to elucidate how this idiom is used in Rust's handling of &lt;code&gt;Mutex&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Experiments and observations
&lt;/h3&gt;

&lt;p&gt;We hold a simple &lt;code&gt;i32&lt;/code&gt; value inside a &lt;code&gt;Mutex&lt;/code&gt;, then operate on it, observe the behavior of the code and convince ourselves why the behavior is that way!&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;use&lt;/span&gt; &lt;span class="nn"&gt;std&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;sync&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Mutex&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="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Mutex&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="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;         &lt;span class="c1"&gt;// Just an i32 value inside a mutex&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;guard&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// &amp;lt;-- 'guard' is of type `MutexGuard`&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;"guard -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;guard&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;"Mutex itself -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a_mutex&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;"Good bye!"&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 output is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;guard -&amp;gt; 5
Mutex itself -&amp;gt; Mutex &lt;span class="o"&gt;{&lt;/span&gt; data: &amp;lt;locked&amp;gt;, poisoned: &lt;span class="nb"&gt;false&lt;/span&gt;, .. &lt;span class="o"&gt;}&lt;/span&gt;
Good bye!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Inside itself, the &lt;code&gt;Mutex&lt;/code&gt; is holding its own &lt;code&gt;data&lt;/code&gt; in a &lt;em&gt;Locked&lt;/em&gt; state. Then the program ends, and the lock is released. But, where is that &lt;code&gt;MutexGuard&lt;/code&gt; coming from? &lt;/p&gt;

&lt;p&gt;Here's what the rust-lang documentation says, of the &lt;code&gt;lock&lt;/code&gt; method:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--safylXLg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w87n2ddcna6j7kzit6y7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--safylXLg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w87n2ddcna6j7kzit6y7.png" alt="The portion of Mutex.lock() from Rust API doc" width="800" height="210"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It returns a &lt;code&gt;LockResult&lt;/code&gt;, which when transformed using an &lt;code&gt;unwrap()&lt;/code&gt; like in the code above, produces a &lt;code&gt;MutexGuard&lt;/code&gt; which is guarding an &lt;code&gt;i32&lt;/code&gt; (the type T) in this case.&lt;/p&gt;

&lt;p&gt;What it we try to acquuire the lock again, on the same &lt;code&gt;a_mutex&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;use&lt;/span&gt; &lt;span class="nn"&gt;std&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;sync&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Mutex&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="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Mutex&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="mi"&gt;5&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;guard&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// &amp;lt;-- 'guard' is of type `MutexGuard`&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;"guard -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;guard&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;"Mutex itself -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="c1"&gt;// An attempt to acquire the lock again.&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&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;"Good bye!"&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;This time, the output is:&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;guard&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;
&lt;span class="n"&gt;Mutex&lt;/span&gt; &lt;span class="n"&gt;itself&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;Mutex&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;locked&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;poisoned&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;false&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;The program &lt;strong&gt;never&lt;/strong&gt; terminates (it cannot even say 'Good Bye')! Why? This is what the documentation says:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The exact behavior on locking a mutex in the thread which already holds the lock is left unspecified. However, this function will not return on the second call (it might panic or deadlock, for example).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In our case, we made a second call, on a mutex, in the same thread (the &lt;em&gt;main&lt;/em&gt; thread here, there is only one)!&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Mutex&lt;/code&gt; has a helpful alternative, in the form of &lt;code&gt;Mutex::try_lock()&lt;/code&gt;, which allows us to attempt to acquire the lock, &lt;strong&gt;knowing&lt;/strong&gt; that we may &lt;strong&gt;fail&lt;/strong&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;use&lt;/span&gt; &lt;span class="nn"&gt;std&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;sync&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Mutex&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="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Mutex&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="mi"&gt;5&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;guard&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// &amp;lt;-- 'guard' is of type `MutexGuard`&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;"guard -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;guard&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;"Mutex itself -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="c1"&gt;// An attempt to acquire the lock again.&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="nf"&gt;.try_lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&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;"Good bye!"&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;This time, the output is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;guard -&amp;gt; 5
Mutex itself -&amp;gt; Mutex &lt;span class="o"&gt;{&lt;/span&gt; data: &amp;lt;locked&amp;gt;, poisoned: &lt;span class="nb"&gt;false&lt;/span&gt;, .. &lt;span class="o"&gt;}&lt;/span&gt;
thread &lt;span class="s1"&gt;'main'&lt;/span&gt; panicked at &lt;span class="s1"&gt;'called `Result::unwrap()` on an `Err` value: "WouldBlock"'&lt;/span&gt;, src/main.rs:37:32
note: run with &lt;span class="sb"&gt;`&lt;/span&gt;&lt;span class="nv"&gt;RUST_BACKTRACE&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;1&lt;span class="sb"&gt;`&lt;/span&gt; environment variable to display a backtrace
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The error message is quite explanatory. The attempt to acquire the lock again, fails because the it will have caused a forever blocking and therefore, non-termination of the program as we have seen eariler.&lt;/p&gt;

&lt;p&gt;The point of interest is this part from rust-lang documentation:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;This function will block the local thread until it is available to acquire the mutex. Upon returning, the thread is the only thread with the lock held. An &lt;strong&gt;RAII guard is returned&lt;/strong&gt; to allow scoped unlock of the lock. When the guard &lt;strong&gt;goes out of scope&lt;/strong&gt;, the mutex will be &lt;strong&gt;unlocked&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The type of this RAII guard is &lt;code&gt;MutexGuard&lt;/code&gt;, (my comment on the code-snippet). What is its purpose in life?&lt;/p&gt;

&lt;p&gt;Again, rust-lang documentation tells us in comforting details:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;An RAII implementation of a “scoped lock” of a mutex. When this structure is dropped (falls out of scope), the lock will be unlocked.&lt;br&gt;
The data protected by the mutex can be accessed through this guard via its Deref and DerefMut implementations.&lt;br&gt;
This structure is &lt;strong&gt;created by the lock&lt;/strong&gt; and try_lock methods on Mutex.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The key portion, in our context, is this: "When this structure is dropped (falls out of scope), the lock will be unlocked".&lt;/p&gt;

&lt;h3&gt;
  
  
  In search of the 'Scope'
&lt;/h3&gt;

&lt;p&gt;Let us try and find out what is the scope of the guard.&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;use&lt;/span&gt; &lt;span class="nn"&gt;std&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;sync&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Mutex&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;a_mutex&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Mutex&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="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="p"&gt;{&lt;/span&gt;   &lt;span class="c1"&gt;// &amp;lt;-- Beginning of scope&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;guard&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// &amp;lt;-- 'guard' is of type `MutexGuard`&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;"guard -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;guard&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;   &lt;span class="c1"&gt;// &amp;lt;-- End of scope`&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;"Mutex itself -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a_mutex&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;"Good bye!"&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 output is quite as expected.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;guard -&amp;gt; 5
Mutex itself -&amp;gt; Mutex &lt;span class="o"&gt;{&lt;/span&gt; data: 5, poisoned: &lt;span class="nb"&gt;false&lt;/span&gt;, .. &lt;span class="o"&gt;}&lt;/span&gt;
Good bye!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Don't miss the fact that &lt;code&gt;Mutex { data: 5, poisoned: false, .. }&lt;/code&gt; indicates the absence of the lock being held, as opposed to the output that we have seen earlier: &lt;code&gt;Mutex { data: &amp;lt;locked&amp;gt;, poisoned: false, .. }&lt;/code&gt;. The following achieves the same effect, for the same reason:&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;use&lt;/span&gt; &lt;span class="nn"&gt;std&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;sync&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Mutex&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;a_mutex&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Mutex&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="mi"&gt;5&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;guard&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// &amp;lt;-- 'guard' is of type `MutexGuard`&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;"guard -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;guard&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nf"&gt;drop&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;guard&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;  &lt;span class="c1"&gt;// &amp;lt;-- Dropping manually!&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;"Mutex itself -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a_mutex&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;"Good bye!"&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 output is exactly the same as the precding output ( &lt;em&gt;no lock&lt;/em&gt; ).&lt;/p&gt;

&lt;p&gt;We establish then, that when the guard is dropped, the lock is released &lt;strong&gt;automatically&lt;/strong&gt;, as per the premise of RAII (or OBRM, if you like). But, when is it constructed exactly?&lt;/p&gt;

&lt;p&gt;Let's be a bit adventurous and peep into the implementation of &lt;code&gt;std::sync::Mutex.rs&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="nd"&gt;#[stable(feature&lt;/span&gt; &lt;span class="nd"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"rust1"&lt;/span&gt;&lt;span class="nd"&gt;,&lt;/span&gt; &lt;span class="nd"&gt;since&lt;/span&gt; &lt;span class="nd"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"1.0.0"&lt;/span&gt;&lt;span class="nd"&gt;)]&lt;/span&gt;
    &lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;lock&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="n"&gt;LockResult&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;MutexGuard&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nv"&gt;'_&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;unsafe&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.inner&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
            &lt;span class="nn"&gt;MutexGuard&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="k"&gt;self&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;Let's ignore everything except, the return type and the call to &lt;code&gt;MutexGuard::new(self)&lt;/code&gt;. Even without much knowledge about the internals, it is quite clear that when &lt;code&gt;Mutex::lock()&lt;/code&gt; returns, it carries with itself, freshly built &lt;code&gt;MutexGuard&lt;/code&gt; object. Just before that happens, a lock resource (Operating System resource) has been obtained. The initialization has guaranteed the acquisition! &lt;/p&gt;

&lt;p&gt;How about release of the lock? Again, peeping into the source of &lt;code&gt;std::sync::Mutex.rs&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="nd"&gt;#[stable(feature&lt;/span&gt; &lt;span class="nd"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"rust1"&lt;/span&gt;&lt;span class="nd"&gt;,&lt;/span&gt; &lt;span class="nd"&gt;since&lt;/span&gt; &lt;span class="nd"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"1.0.0"&lt;/span&gt;&lt;span class="nd"&gt;)]&lt;/span&gt;
&lt;span class="k"&gt;impl&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;T&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="nb"&gt;Sized&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Drop&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;MutexGuard&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nv"&gt;'_&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;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;drop&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="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;unsafe&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.lock.poison&lt;/span&gt;&lt;span class="nf"&gt;.done&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="py"&gt;.poison&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.lock.inner&lt;/span&gt;&lt;span class="nf"&gt;.unlock&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="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The key point for us is that &lt;code&gt;self.lock.inner.unlock()&lt;/code&gt; statement. As the &lt;code&gt;MutexGuard&lt;/code&gt; is dropped, the lock is released!&lt;/p&gt;

&lt;p&gt;Therefore, the &lt;strong&gt;scope&lt;/strong&gt; in which a &lt;code&gt;MutexGuard&lt;/code&gt; remains valid, follows the idiom of &lt;strong&gt;RAII&lt;/strong&gt;!&lt;/p&gt;

&lt;h3&gt;
  
  
  The temporary MutexGuard
&lt;/h3&gt;

&lt;p&gt;The preceding &lt;a href="https://dev.to/nsengupta/rust-notes-on-temporary-values-in-method-call-expressions-1-1g8"&gt;article&lt;/a&gt; in this series discusses the concept of temporary variable. One of the takeaways from that is the presence of a &lt;em&gt;receiver&lt;/em&gt;, which is &lt;em&gt;temporarily&lt;/em&gt; produced to complete the method-call expression.&lt;/p&gt;

&lt;p&gt;The concept of this temporary object is applicable in the case of &lt;code&gt;MutexGuard&lt;/code&gt; here too. And, following the scoping rules of a temporary, the &lt;code&gt;MutexGuard&lt;/code&gt; ceases to exist at the end of the statement.&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;use&lt;/span&gt; &lt;span class="nn"&gt;std&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nn"&gt;sync&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Mutex&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;a_mutex&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Mutex&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="mi"&gt;5&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;guard&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="nf"&gt;.lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.to_string&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// &amp;lt;-- 'guard' is of type `String`&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;"Mutex itself -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// &amp;lt;-- MutexGuard is not being held&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;"guard -&amp;gt; {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;guard&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="c1"&gt;// An attempt to acquire the lock again.&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;w&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a_mutex&lt;/span&gt;&lt;span class="nf"&gt;.try_lock&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&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;"Good bye!"&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;Nothing surprising about the output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;guard -&amp;gt; &lt;span class="s2"&gt;"5"&lt;/span&gt;
Mutex itself -&amp;gt; Mutex &lt;span class="o"&gt;{&lt;/span&gt; data: 5, poisoned: &lt;span class="nb"&gt;false&lt;/span&gt;, .. &lt;span class="o"&gt;}&lt;/span&gt;
Good bye!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice the absence of any &lt;code&gt;data: &amp;lt;locked&amp;gt;&lt;/code&gt; in the Mutex. When the preceding statement ends - yielding the stringified representation of value '5' - the tempoary MutexGuard&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  reaches the end of its &lt;em&gt;scope&lt;/em&gt;,&lt;/li&gt;
&lt;li&gt;  is dropped, and therefore&lt;/li&gt;
&lt;li&gt;  releases the lock (re: RAII)&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;We have read the value that is fenced in by the Mutex and have trodden in the world of &lt;strong&gt;expressions&lt;/strong&gt; along with temporary objects. In the next article in this series, we explore more about how the &lt;strong&gt;scope&lt;/strong&gt; of the temporaries is affected by the body of an expression.&lt;/p&gt;

&lt;h3&gt;
  
  
  Main Takeaways
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;code&gt;Mutex&lt;/code&gt; follows the idiom of RAII (or OBRM) for ensuring that access to the value it is guarding, cannot be breached.&lt;/li&gt;
&lt;li&gt;  &lt;code&gt;Mutex.lock()&lt;/code&gt; produces a temporary &lt;code&gt;MutexGuard&lt;/code&gt; whose construction and destruction ( Drop ), acquires and releases the lock, in that order.&lt;/li&gt;
&lt;li&gt;  Because it is a temporary object, the &lt;code&gt;MutexGuard&lt;/code&gt; is dropped at the end of the statement that creates it, unless it scope is expanded by other means (that is not a part of this article though).&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>rust</category>
      <category>mutex</category>
    </item>
    <item>
      <title>Rust Notes on Temporary values (usage of Mutex) - 1</title>
      <dc:creator>Nirmalya Sengupta</dc:creator>
      <pubDate>Wed, 14 Jun 2023 04:20:53 +0000</pubDate>
      <link>https://forem.com/nsengupta/rust-notes-on-temporary-values-in-method-call-expressions-1-1g8</link>
      <guid>https://forem.com/nsengupta/rust-notes-on-temporary-values-in-method-call-expressions-1-1g8</guid>
      <description>&lt;p&gt;[Cover image credit: &lt;a href="https://pixabay.com/users/engin_akyurt-3656355"&gt;https://pixabay.com/users/engin_akyurt-3656355&lt;/a&gt;]&lt;/p&gt;

&lt;h3&gt;
  
  
  The build up
&lt;/h3&gt;

&lt;p&gt;Just like other enthusiastic Rust newbies, I am trying to trek through the difficult terrain of Rust's Borrow-checker, with excitement,  mixed with trepidation. Many times, I fall foul of the compiler, because I am careless or I lose sight of the obvious. But, some other times, compiler's reprimands baffle me, to no end.&lt;/p&gt;

&lt;p&gt;One such case is of compiler flagging: temporary values getting freed at the end of the statement! &lt;/p&gt;

&lt;p&gt;A method-call expression like:&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;a&lt;/span&gt;&lt;span class="nf"&gt;.b&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.c&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="py"&gt;.d&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;is so common in a program that one tends to write it, almost by reflex. Yet, some times the compiler derails the line of thought, unexpectedly, pointing out release of a temporary variable, that one hasn't even mentioned.&lt;/p&gt;

&lt;p&gt;I had decided to understand the whys and the wherefores of this particular problem, to reasonably good extent. At least, I should know how to avoid those. This is a digest of that exploration.&lt;/p&gt;

&lt;h3&gt;
  
  
  Simulate the error
&lt;/h3&gt;

&lt;p&gt;An &lt;code&gt;Employee&lt;/code&gt; has an id ( &lt;code&gt;i32&lt;/code&gt; ). It implements a &lt;code&gt;get_details()&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;This method, intentionally, returns a new &lt;code&gt;Details&lt;/code&gt; Object (the reason behind this, will be clearer later). The object initializes the &lt;code&gt;name&lt;/code&gt; field with a String constant, which it &lt;em&gt;owns&lt;/em&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="nd"&gt;#[derive(Debug)]&lt;/span&gt;
&lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;Employee&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;id&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="nd"&gt;#[derive(Debug)]&lt;/span&gt;
&lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;Details&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;emp_id&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="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;impl&lt;/span&gt; &lt;span class="n"&gt;Employee&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;get_details&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="n"&gt;Details&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;Details&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;emp_id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&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;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Nirmalya"&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="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;impl&lt;/span&gt; &lt;span class="n"&gt;Details&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;get_name&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;String&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.name&lt;/span&gt;
    &lt;span class="p"&gt;}&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="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Employee&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;10&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;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="nf"&gt;.get_details&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.get_name&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;"Employee name: {}"&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="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The compiler frowns, expectedly ...&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;error[E0507]: cannot move out of &lt;span class="sb"&gt;`&lt;/span&gt;self.name&lt;span class="sb"&gt;`&lt;/span&gt; which is behind a shared reference
  &lt;span class="nt"&gt;--&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; src/main.rs:31:9
   |
31 |         self.name
   |         ^^^^^^^^^ move occurs because &lt;span class="sb"&gt;`&lt;/span&gt;self.name&lt;span class="sb"&gt;`&lt;/span&gt; has &lt;span class="nb"&gt;type&lt;/span&gt; &lt;span class="sb"&gt;`&lt;/span&gt;String&lt;span class="sb"&gt;`&lt;/span&gt;, which does not implement the &lt;span class="sb"&gt;`&lt;/span&gt;Copy&lt;span class="sb"&gt;`&lt;/span&gt; trait
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are not allowed to 'move' the name here; the &lt;code&gt;&amp;amp;self&lt;/code&gt; parameter is prohibiting it. The move requires the &lt;code&gt;Details&lt;/code&gt; to be modified. The &lt;code&gt;get_details()&lt;/code&gt; method taken in an immutable reference: &lt;code&gt;&amp;amp;self&lt;/code&gt;. After the method returns, &lt;code&gt;self.name&lt;/code&gt; cannot remain uninitialized.&lt;/p&gt;

&lt;p&gt;We cannot move but we can possibly share a reference then?&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="n"&gt;Details&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;get_name&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="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nb"&gt;String&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;  &lt;span class="c1"&gt;// String is replaced with &amp;amp;String&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="py"&gt;.name&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 compiler finds the temporary which is freed prematurely, this time.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;error[E0716]: temporary value dropped &lt;span class="k"&gt;while &lt;/span&gt;borrowed
  &lt;span class="nt"&gt;--&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; src/main.rs:41:13
   |
41 |     &lt;span class="nb"&gt;let &lt;/span&gt;n &lt;span class="o"&gt;=&lt;/span&gt; e.get_details&lt;span class="o"&gt;()&lt;/span&gt;.get_name&lt;span class="o"&gt;()&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   |             ^^^^^^^^^^^^^^^           - temporary value is freed at the end of this statement
   |             |
   |             creates a temporary value which is freed &lt;span class="k"&gt;while &lt;/span&gt;still &lt;span class="k"&gt;in &lt;/span&gt;use
42 |
43 |     println!&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Employee name: {}"&lt;/span&gt;, n&lt;span class="o"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;     
   |                                   - borrow later used here
   |
&lt;span class="nb"&gt;help&lt;/span&gt;: consider using a &lt;span class="sb"&gt;`&lt;/span&gt;&lt;span class="nb"&gt;let&lt;/span&gt;&lt;span class="sb"&gt;`&lt;/span&gt; binding to create a longer lived value
   |
41 ~     &lt;span class="nb"&gt;let &lt;/span&gt;binding &lt;span class="o"&gt;=&lt;/span&gt; e.get_details&lt;span class="o"&gt;()&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
42 ~     &lt;span class="nb"&gt;let &lt;/span&gt;n &lt;span class="o"&gt;=&lt;/span&gt; binding.get_name&lt;span class="o"&gt;()&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   |

For more information about this error, try &lt;span class="sb"&gt;`&lt;/span&gt;rustc &lt;span class="nt"&gt;--explain&lt;/span&gt; E0716&lt;span class="sb"&gt;`&lt;/span&gt;&lt;span class="nb"&gt;.&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, changing the body and return type of &lt;code&gt;Details::get_details()&lt;/code&gt; is causing an otherwise harmelss method-call expression to fail. &lt;/p&gt;

&lt;p&gt;But why? Let's find out more about this.&lt;/p&gt;

&lt;h3&gt;
  
  
  Elaboration
&lt;/h3&gt;

&lt;p&gt;A binding comes into existence with the &lt;code&gt;let&lt;/code&gt; statement: &lt;code&gt;e&lt;/code&gt; is bound to and thereby is owning an &lt;code&gt;Employee&lt;/code&gt; struct(ure).&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;e&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Employee&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt; &lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are trying get an access to the Employee's name. This &lt;strong&gt;name&lt;/strong&gt; is not a part of &lt;code&gt;Employee&lt;/code&gt; but of a different object of type &lt;code&gt;Details&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="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="nf"&gt;.get_details&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.get_name&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What &lt;code&gt;get_details()&lt;/code&gt; produces is a &lt;code&gt;Details&lt;/code&gt; object. We are calling &lt;code&gt;get_name()&lt;/code&gt; on it. What's there to complain about?&lt;/p&gt;

&lt;p&gt;Well, the &lt;code&gt;get_name()&lt;/code&gt; is returning a reference to a member variable of &lt;code&gt;Details&lt;/code&gt;. For this reference to remain valid (pointing to some place which is initialized with some known value), &lt;code&gt;Details&lt;/code&gt; has to keep existing. But, till when? The answer lies in establishing its &lt;em&gt;scope&lt;/em&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Expresssions and Scopes
&lt;/h3&gt;

&lt;p&gt;This is a method-call &lt;a href="[https://](https://doc.rust-lang.org/stable/reference/expressions/method-call-expr.html)"&gt;expression&lt;/a&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="n"&gt;e&lt;/span&gt;&lt;span class="nf"&gt;.get_details&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.get_name&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;get_details()&lt;/code&gt; is a direct method on the type &lt;code&gt;Employee&lt;/code&gt;. Here, &lt;code&gt;e&lt;/code&gt; is called the receiver of method-call.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;get_name()&lt;/code&gt; is a direct method on the type &lt;code&gt;Details&lt;/code&gt;. But, where is the receiver of this method-call? Taking a closer look, we find that an unnamed object of type &lt;code&gt;Details&lt;/code&gt; has been made available - &lt;em&gt;temporarily&lt;/em&gt; - so that we can call the method. Our intention is to be able to get hold of what &lt;code&gt;get_name()&lt;/code&gt; returns. We don't really care about this faceless helper object, though. &lt;/p&gt;

&lt;p&gt;The key understanding here, is that &lt;code&gt;get_name()&lt;/code&gt; returns a &lt;strong&gt;reference&lt;/strong&gt;. It refers to a field of &lt;code&gt;Details&lt;/code&gt; object. If and when this (temporary) &lt;code&gt;Details&lt;/code&gt; object ceases to exist (or &lt;em&gt;Drop&lt;/em&gt;-ped, if you like), the reference is invalidated. &lt;/p&gt;

&lt;p&gt;By the rule of scope of such temporaries (&lt;a href="[https://](https://doc.rust-lang.org/stable/reference/expressions.html?highlight=temporary#temporaries)"&gt;more here&lt;/a&gt;), they can live till the end of the statement that contains the call that produces it. Interpeting this vis-a-vis our example,  by the time the whole expression is evaluated and the statement ends, the faceless &lt;code&gt;Details&lt;/code&gt; object has gone out of existence. Therefore, it is illegal to hold a reference to a field that it owns. So, &lt;code&gt;n&lt;/code&gt; cannot be assigned to.&lt;/p&gt;

&lt;p&gt;This explains the complaint from the compiler, shown above.&lt;/p&gt;

&lt;h3&gt;
  
  
  Going a little further
&lt;/h3&gt;

&lt;p&gt;One way, not to let the faceless &lt;code&gt;Details&lt;/code&gt; object go, is to bind it to a memory location.&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="n"&gt;e&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Employee&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;10&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;intermediate_d&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="nf"&gt;.get_details&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// &amp;lt;--- Binding!&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;intermediate_d&lt;/span&gt;&lt;span class="nf"&gt;.get_name&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;    &lt;span class="c1"&gt;// &amp;lt;--- Method call expression&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;"Employee name: {}"&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="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, the compiler is happy and waves us ahead. But, why exactly?&lt;br&gt;
Because we have bound the hitherto faceless &lt;code&gt;Details&lt;/code&gt; object to &lt;code&gt;intermediate_d&lt;/code&gt;, its scope has now been extended to the end of the block it belongs to (in this case, the end of the body of function, i.e.,&lt;code&gt;main()&lt;/code&gt;). Thus, getting hold of the &lt;code&gt;name&lt;/code&gt; inside it, is not illegal anymore.&lt;/p&gt;

&lt;p&gt;This was what the ever helpful Rust compiler suggested in the error message, shown earlier! 👌 🌟&lt;/p&gt;

&lt;p&gt;Interestingly, the following code is flagged as alright, by the compiler.&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="n"&gt;e&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Employee&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;10&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;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="nf"&gt;.get_details&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.get_name&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.len&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// &amp;lt;-- expression produces a value.&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;"Employee name: {} chars long"&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="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, the length of the name is what we hold in &lt;code&gt;n&lt;/code&gt;. The faceless &lt;code&gt;Details&lt;/code&gt; object, goes away by the end of the statement, but it doesn't matter. We are not holding any reference to &lt;code&gt;Details.name&lt;/code&gt; anyway.&lt;/p&gt;

&lt;p&gt;Even this works, but for a slightly different reason:&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="n"&gt;Details&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;get_name&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;String&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;self&lt;/span&gt;&lt;span class="py"&gt;.name&lt;/span&gt;&lt;span class="nf"&gt;.to_owned&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;  &lt;span class="c1"&gt;// &amp;lt;-- Not a reference, but a cloned value, unassociated with `self.name`&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="c1"&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="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;Employee&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;10&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;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="nf"&gt;.get_details&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.get_name&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;"Employee name: {}"&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="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because &lt;code&gt;get_name&lt;/code&gt; returns a value that is owned by - and not referred to by - the caller, the non-existence of the faceless &lt;code&gt;Details&lt;/code&gt; object is immaterial here. &lt;code&gt;n&lt;/code&gt; is bound to a fresh replica of what was held by &lt;code&gt;Details.name&lt;/code&gt;. Its scope extends till the end of the block; in this case, the end of body of function, i.e., &lt;code&gt;main()&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Main Takeaways
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Method chains are &lt;em&gt;Method-call expressions&lt;/em&gt;. Like every expression, they evaluate to a value.&lt;/li&gt;
&lt;li&gt;Every  dot ( . ) operation is a method/function, which operates on an object, called the 'Receiver' according to the Book (rust book). The receiver's type must have that method defined on itself.&lt;/li&gt;
&lt;li&gt;In some cases, in order to determine the intended receiver, the compiler follows the references along the expression and produces temporary objects as receivers. The scope of these temporary objects extends up to the end of the statement they are contained in (not exactly, but let's continue till subsequent articles on this topic). Therefore, the compiler considers any attempt to access these temporary objects through references, after the statement, as illegal.&lt;/li&gt;
&lt;li&gt;The simplest way to avoid this, is to declare local variables to bind to these temporary objects. The helpful compiler even hints at this, along with the error message.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Acknowledgements
&lt;/h2&gt;

&lt;p&gt;In my quest to understand the behaviour of the compiler in this case, I have gone through a number of articles / blogs / explanations. I will be unfair and utterly discourteous on my part, if I don't mention at least, some of them. This blog stands on the shoulders of those authors and elaborators:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://fasterthanli.me/articles/a-rust-match-made-in-hell"&gt;https://fasterthanli.me/articles/a-rust-match-made-in-hell&lt;/a&gt; from one of the most readable and elucidative take on all things Rust, by Amos ( @fasterthanlime ).&lt;/li&gt;
&lt;li&gt;A brief yet illuminative &lt;a href="[https://](https://stackoverflow.com/questions/72777453/mutex-locking-inside-loop-declaration)"&gt;answer&lt;/a&gt; by Sven &lt;a href="[https://](https://stackoverflow.com/users/279627/sven-marnach)"&gt;Marnach&lt;/a&gt; on Stackoverflow.&lt;/li&gt;
&lt;li&gt;An useful question on Stackoverflow by &lt;a href="https://stackoverflow.com/users/318206/bosh"&gt;Bosh&lt;/a&gt; and fantastic answer by Jim &lt;a href="https://stackoverflow.com/users/406309/jim-blandy"&gt;Blandy&lt;/a&gt;. This answer has brought forth that &lt;strong&gt;Aha&lt;/strong&gt; moment for me but the discussion trail itself is very helpful (thanks everyone else, in that ticket).&lt;/li&gt;
&lt;li&gt;The chapter on &lt;em&gt;Destruction&lt;/em&gt; in the Rust &lt;a href="https://rustwiki.org/en/reference/destructors.html#destructors"&gt;wiki&lt;/a&gt; and a bit of my own expeimentation
&lt;/li&gt;
&lt;li&gt;An old but quite useful explanation of &lt;a href="(https://vojtechkral.github.io/blag/rust-drop-order/)"&gt;scoping&lt;/a&gt;; recommended!&lt;/li&gt;
&lt;li&gt;Of course, the relevant &lt;a href="https://rustwiki.org/en/reference/destructors.html#temporary-scopes"&gt;pages&lt;/a&gt; of The Rust Wiki, an excellent aid for a newbie like me.&lt;/li&gt;
&lt;li&gt;My companion &lt;a href="https://www.oreilly.com/library/view/programming-rust-2nd/9781492052586/"&gt;book&lt;/a&gt; by Jim Blandy (again!), Jason Orendorff, Leonora Tindall&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>rust</category>
    </item>
    <item>
      <title>Random Rust Notes - 4</title>
      <dc:creator>Nirmalya Sengupta</dc:creator>
      <pubDate>Sat, 29 Apr 2023 17:25:34 +0000</pubDate>
      <link>https://forem.com/nsengupta/random-rust-notes-4-4jjh</link>
      <guid>https://forem.com/nsengupta/random-rust-notes-4-4jjh</guid>
      <description>&lt;p&gt;[Cover image credit: &lt;a href="https://pixabay.com/users/engin_akyurt-3656355"&gt;https://pixabay.com/users/engin_akyurt-3656355&lt;/a&gt;]&lt;/p&gt;

&lt;p&gt;This blog is a collection of notes of key learnings / understandings / &lt;em&gt;Aha&lt;/em&gt; moments, as I am kayaking through demanding yet exciting waters, of Rust ( #rustlang ). If you happen to find defects in the code or gaps in my understanding, please correct me. I will remain thankful.&lt;/p&gt;

&lt;p&gt;The topic of this particular notes: &lt;em&gt;scoped_threads&lt;/em&gt; in Rust.&lt;/p&gt;

&lt;h3&gt;
  
  
  A brief on spawned threads
&lt;/h3&gt;

&lt;p&gt;Using the standard library, whenever a thread is launched - &lt;code&gt;spawn&lt;/code&gt;-ed - a unit of execution - - with an associated piece of logic - is created.  Underneath, the library, OS facilities and hardware work together to run that &lt;em&gt;unit of execution&lt;/em&gt; , &lt;strong&gt;separately&lt;/strong&gt; from the unit of execution that launched it. This is at the core of threading - a bit simplistic, I agree  - concept. One is the parent thread and it launches a child thread, as is commonly understood.&lt;/p&gt;

&lt;p&gt;Naturally, the child thread will finish its job at some point in time. The parent thread may need to know if and when that happens (let us keep away from the aspect of &lt;em&gt;cancellation&lt;/em&gt; of the child thread for the time being). A mechanism must exist for it to be able to do that. This mechanism takes the form of a handle (programmer-speak). Using this handle, the parent thread waits for the child thread to &lt;code&gt;join&lt;/code&gt; the former and then, the flow of execution continues.&lt;/p&gt;

&lt;h3&gt;
  
  
  So, we need a handle
&lt;/h3&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;fn&lt;/span&gt; &lt;span class="nf"&gt;start_as_free&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="n"&gt;JoinHandle&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;message_collector_handle&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;thread&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;spawn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;move&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="p"&gt;});&lt;/span&gt;
        &lt;span class="n"&gt;message_collector_handle&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here's a skeleton code: a thread is &lt;code&gt;spawn&lt;/code&gt;-ed and its handle is returned to the caller (the parent thread). For a better understanding of what that &lt;code&gt;JoinHandle&lt;/code&gt; is, here's the standard library's &lt;a href="%5BJoinHandle%20in%20std::thread%20-%20Rust%5D(https://doc.rust-lang.org/stable/std/thread/struct.JoinHandle.html)"&gt;documentation&lt;/a&gt;. &lt;code&gt;JoinHandle&lt;/code&gt; is a structure of type &lt;code&gt;std::thread::JoinHandle&lt;/code&gt;. One of its implementation functions is named join, &lt;code&gt;pub fn join(self) -&amp;gt; Result&amp;lt;T&amp;gt;&lt;/code&gt;. This is the mechanism available to the parent thread, to wait for the child thread to finish. From the standard library's documentation:&lt;/p&gt;

&lt;h3&gt;
  
  
  Now, a scoped thread
&lt;/h3&gt;

&lt;p&gt;Instead of spawning a free-running thread as shown above, a parent thread may launch a &lt;em&gt;scoped&lt;/em&gt; thread. A scoped thread, is built in a way which ensures that the function in which it is launched will finish only when the threads launched inside it are also finished. This is a key aspect because a scoped thread cannot &lt;em&gt;live beyond&lt;/em&gt; the demarcation laid out by its parent thread. Therefore, the parent thread may share its own data structures with the child thread, secure in the understanding that all the changes (if any) done to these data structures by the child thread, are guaranteed to be visible to the parent. &lt;/p&gt;

&lt;p&gt;From the standard library's documentation:&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;ScopedJoinHandle&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nv"&gt;'scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;T&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;_&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, &lt;code&gt;ScopedJoinHandle&lt;/code&gt; is a structure, much like its elder sibling &lt;code&gt;JoinHandle&lt;/code&gt; (elder, because it preexists). And, sure enough, it has a &lt;code&gt;join()&lt;/code&gt; function as well. But with a twist!&lt;/p&gt;

&lt;h3&gt;
  
  
  Difference between spawning steps
&lt;/h3&gt;

&lt;p&gt;A standard, your-friendly-companion-thread is spawned thus:&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;message_collector_handle&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;thread&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;spawn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;move&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="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A scoped, strictly-watched-and-controlled thread, is spawned thus:&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;message_collector_handle&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;thread&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;scope&lt;/span&gt; &lt;span class="p"&gt;(|&lt;/span&gt;&lt;span class="n"&gt;current_scope&lt;/span&gt;&lt;span class="p"&gt;|&lt;/span&gt; 
                               &lt;span class="p"&gt;{&lt;/span&gt;
                                  &lt;span class="n"&gt;current_scope&lt;/span&gt;&lt;span class="nf"&gt;.spawn&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="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;Something special is happening in &lt;code&gt;std::hread::scope()&lt;/code&gt; . From standard library's documentation:&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;fn&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nv"&gt;'env&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;F&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;T&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;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;F&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;T&lt;/span&gt;
&lt;span class="k"&gt;where&lt;/span&gt;
    &lt;span class="n"&gt;F&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nv"&gt;'scope&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;FnOnce&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nv"&gt;'scope&lt;/span&gt; &lt;span class="n"&gt;Scope&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nv"&gt;'scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;'env&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;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;T&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, the &lt;code&gt;scope&lt;/code&gt; function takes in a closure as a parameter, which in turn takes in a &lt;code&gt;Scope&lt;/code&gt; (with uppercase 'S')  value as a paremeter.&lt;/p&gt;

&lt;p&gt;What is that &lt;code&gt;Scope&lt;/code&gt;? It is a struct! From the standard library's documentation:&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;Scope&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nv"&gt;'scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;'env&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;'scope&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="cm"&gt;/* private fields */&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And, as expected, this struct implements a &lt;code&gt;spawn&lt;/code&gt; function:&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;fn&lt;/span&gt; &lt;span class="n"&gt;spawn&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;F&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;T&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nv"&gt;'scope&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;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;F&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;ScopedJoinHandle&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nv"&gt;'scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;T&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;F&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nf"&gt;FnOnce&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;T&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nb"&gt;Send&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nv"&gt;'scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;T&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;Send&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nv"&gt;'scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let us not get lost in that crowd of symbols. The key understanding:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;thread::scope&lt;/code&gt; takes in a closure. This closure, in turn, takes in a &lt;code&gt;Scope&lt;/code&gt; value. Inside the closure, a thread is spawned: &lt;code&gt;Scope::spawn()&lt;/code&gt;. This &lt;code&gt;spawn()&lt;/code&gt; call returns a &lt;code&gt;ScopedJoinHandle&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The return value of type &lt;code&gt;ScopedJoinHandle&lt;/code&gt; is valid as long as the parameters are valid. Put another way, the return value (remember, this is a &lt;code&gt;struct&lt;/code&gt; ) cannot live even when the &lt;code&gt;Scope&lt;/code&gt; (the struct, starts with an uppercase 'S'!) doesn't.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  An example makes it clearer, hopefully!
&lt;/h3&gt;

&lt;p&gt;Let's watch these two functions, being compiled:&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;fn&lt;/span&gt; &lt;span class="nf"&gt;start_as_scoped&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="n"&gt;ScopedJoinHandle&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&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="nb"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;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;message_collector_handle&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;thread&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;scope&lt;/span&gt; &lt;span class="p"&gt;(|&lt;/span&gt;&lt;span class="n"&gt;current_scope&lt;/span&gt;&lt;span class="p"&gt;|&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                    &lt;span class="n"&gt;current_scope&lt;/span&gt;&lt;span class="nf"&gt;.spawn&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="p"&gt;})&lt;/span&gt;              
                &lt;span class="p"&gt;});&lt;/span&gt;

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

&lt;span class="c1"&gt;// Here's our old friend, std::thread::JoinHandle&lt;/span&gt;
&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;start_as_free&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="n"&gt;JoinHandle&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;message_collector_handle&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;thread&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;spawn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;move&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="p"&gt;});&lt;/span&gt;

  &lt;span class="n"&gt;message_collector_handle&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The compiler is watchful, yet helpful:&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;lifetime&lt;/span&gt; &lt;span class="n"&gt;may&lt;/span&gt; &lt;span class="n"&gt;not&lt;/span&gt; &lt;span class="n"&gt;live&lt;/span&gt; &lt;span class="n"&gt;long&lt;/span&gt; &lt;span class="n"&gt;enough&lt;/span&gt;
  &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;src&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;main&lt;/span&gt;&lt;span class="py"&gt;.rs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;21&lt;/span&gt;
   &lt;span class="p"&gt;|&lt;/span&gt;
&lt;span class="mi"&gt;29&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;message_collector_handle&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; 
                &lt;span class="nn"&gt;thread&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;scope&lt;/span&gt; &lt;span class="p"&gt;(|&lt;/span&gt;&lt;span class="n"&gt;current_scope&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="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;type&lt;/span&gt; &lt;span class="n"&gt;of&lt;/span&gt; &lt;span class="n"&gt;closure&lt;/span&gt; &lt;span class="n"&gt;is&lt;/span&gt; &lt;span class="n"&gt;ScopedJoinHandle&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="err"&gt;'&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&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="nb"&gt;String&lt;/span&gt;&lt;span class="o"&gt;&amp;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="n"&gt;has&lt;/span&gt; &lt;span class="k"&gt;type&lt;/span&gt; &lt;span class="err"&gt;`&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="err"&gt;'&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="n"&gt;Scope&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="err"&gt;'&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;'_&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="err"&gt;`&lt;/span&gt;
&lt;span class="mi"&gt;30&lt;/span&gt; &lt;span class="p"&gt;|&lt;/span&gt;                     &lt;span class="n"&gt;current_scope&lt;/span&gt;&lt;span class="nf"&gt;.spawn&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="p"&gt;})&lt;/span&gt;
   &lt;span class="p"&gt;|&lt;/span&gt;                     &lt;span class="o"&gt;^^^^&lt;/span&gt;  &lt;span class="n"&gt;returning&lt;/span&gt; &lt;span class="n"&gt;this&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="n"&gt;requires&lt;/span&gt; &lt;span class="n"&gt;that&lt;/span&gt; &lt;span class="err"&gt;`'&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="err"&gt;`&lt;/span&gt; &lt;span class="n"&gt;must&lt;/span&gt; &lt;span class="n"&gt;outlive&lt;/span&gt; &lt;span class="err"&gt;`'&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="err"&gt;`&lt;/span&gt;

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

&lt;/div&gt;



&lt;p&gt;Hmm! We cannot return the &lt;code&gt;ScopedJoinHandle&lt;/code&gt; in a manner as we could, for its sibling, &lt;code&gt;JoinHandle&lt;/code&gt; .&lt;/p&gt;

&lt;h3&gt;
  
  
  But, why?
&lt;/h3&gt;

&lt;p&gt;Without getting into the details of lifetime, we can analyse it intuitively. &lt;/p&gt;

&lt;p&gt;The &lt;code&gt;ScopedJoinHandle&lt;/code&gt; cannot live beyond the lifetime of the &lt;code&gt;current_scope&lt;/code&gt;. Put in a different way, we cannot let the &lt;code&gt;ScopedJoinHandle&lt;/code&gt;&lt;br&gt;
return from the function, because that will mean that some other thread will be able to &lt;code&gt;join&lt;/code&gt; the thread launched under the watchful eyes of&lt;br&gt;
&lt;code&gt;current_scope&lt;/code&gt;. But that is disallowed. The standard library's documentation makes that very clear:&lt;/p&gt;



&lt;blockquote&gt;
&lt;p&gt;All threads spawned within the scope that haven’t been manually joined will be automatically joined before this function returns.&lt;/p&gt;
&lt;/blockquote&gt;



&lt;p&gt;This means, that either we explicitly &lt;code&gt;join&lt;/code&gt; the thread &lt;em&gt;before&lt;/em&gt; leaving the scope or thread will be implicitly &lt;code&gt;join&lt;/code&gt;-ed by Rust runtime, when the &lt;code&gt;current_scope&lt;/code&gt; is dropped.&lt;/p&gt;

&lt;p&gt;This compiles:&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;fn&lt;/span&gt; &lt;span class="nf"&gt;start_as_scoped&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;i32&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;message_collector_handle&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;thread&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;scope&lt;/span&gt; &lt;span class="p"&gt;(|&lt;/span&gt;&lt;span class="n"&gt;current_scope&lt;/span&gt;&lt;span class="p"&gt;|&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
           &lt;span class="n"&gt;current_scope&lt;/span&gt;&lt;span class="nf"&gt;.spawn&lt;/span&gt;&lt;span class="p"&gt;(||&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="mi"&gt;42&lt;/span&gt; &lt;span class="p"&gt;})&lt;/span&gt;&lt;span class="nf"&gt;.join&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;    &lt;span class="c1"&gt;// &amp;lt;---- join() before leaviing the current_scope&amp;gt;    &lt;/span&gt;
         &lt;span class="p"&gt;});&lt;/span&gt;


        &lt;span class="k"&gt;match&lt;/span&gt; &lt;span class="n"&gt;message_collector_handle&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="n"&gt;x&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;x&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="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="c1"&gt;// We could have returned a String, by modifying the return type of the function to Result&amp;lt;T,E&amp;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;h3&gt;
  
  
  Key takeaways
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  A thread which is spawned inside a &lt;em&gt;scope&lt;/em&gt;, must end before scope ends.&lt;/li&gt;
&lt;li&gt;  Such a thread's handle cannot outlive the overarching &lt;em&gt;scope&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;  Such a thread must be &lt;code&gt;join&lt;/code&gt;-ed explicitly or those will be &lt;code&gt;join&lt;/code&gt;-ed implicitly, at runtime. And, inside the scope!!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;NB: Standard library's documentation on Scoped threads, is elaborate and worth a good reading! &lt;/p&gt;

</description>
      <category>rust</category>
      <category>scopedthreads</category>
    </item>
    <item>
      <title>Random Rust Notes - 3</title>
      <dc:creator>Nirmalya Sengupta</dc:creator>
      <pubDate>Sat, 22 Apr 2023 17:12:09 +0000</pubDate>
      <link>https://forem.com/nsengupta/random-rust-notes-3-2aej</link>
      <guid>https://forem.com/nsengupta/random-rust-notes-3-2aej</guid>
      <description>&lt;p&gt;[Cover image credit: &lt;a href="https://pixabay.com/users/engin_akyurt-3656355"&gt;https://pixabay.com/users/engin_akyurt-3656355&lt;/a&gt;]&lt;/p&gt;

&lt;p&gt;This blog is a collection of notes of key learnings / understandings / Aha moments, as I am kayaking through demanding yet exciting waters, of Rust (#rustlang). If these help someone, I will be happy of course. OTOH, if someone happens to find defects in the code or gaps in my understanding, please correct me. I will remain thankful.&lt;/p&gt;

&lt;p&gt;As a part of a personal project, I am in the middle of learning how to use channels to communicate between two threads. This is quite a common topic. Many people seem to have questions around this topic. Many answers / explanations are available. &lt;/p&gt;

&lt;p&gt;These are my notes, though. &lt;/p&gt;

&lt;h3&gt;
  
  
  Takeaways from the previous note
&lt;/h3&gt;

&lt;p&gt;The previous note is &lt;a href="https://dev.to/nsengupta/random-rust-notes-2-d4n"&gt;here&lt;/a&gt; (for a quick recap, in cases needed)&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Using channels, multiple producers can send messages to a single consumer.&lt;/li&gt;
&lt;li&gt;  Each such producer must have its own copy of the sender-end of the channel. &lt;code&gt;clone&lt;/code&gt; the sender-end for this.&lt;/li&gt;
&lt;li&gt;  Channels are unidirectional and FIFO in structure; therefore, every producer's messages to the consumer reach in the same order in which they are despatched.&lt;/li&gt;
&lt;li&gt;  Multiple producers messages may reach in any random order, though.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  What is it that I am modeling (recap helps)
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;An in-memory dashboard, which 

&lt;ul&gt;
&lt;li&gt;Works as a collector of events generated by a number of event-generators&lt;/li&gt;
&lt;li&gt;Informs a viewer of the events as they are arriving and being collected&lt;/li&gt;
&lt;li&gt;Dumpts a chronicle of the events that it receives before terminating&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Each event generator is modeled as a thread that pushes the events and then terminates&lt;/li&gt;
&lt;li&gt;An event inquirer - another thread itself - which registers itself with the dashboard, so that the dashboard can keep informing it of the events as they arrive&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;All communications between various threads, happen through &lt;em&gt;channels&lt;/em&gt; and are based on an application-specific protocol, implemented as an &lt;code&gt;Enumeration&lt;/code&gt;. Enumumerations help in ensuring that channels are bound to a &lt;em&gt;particular type&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;The dashboard is modeled as a &lt;code&gt;struct&lt;/code&gt;. It has a lifecycle:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Created using a conventional &lt;code&gt;new()&lt;/code&gt; function&lt;/li&gt;
&lt;li&gt;  Prepared with a &lt;code&gt;ready()&lt;/code&gt; function&lt;/li&gt;
&lt;li&gt;  Nudged to receive, events from producers (separate threads, outside the struct) with a &lt;code&gt;start()&lt;/code&gt; function&lt;/li&gt;
&lt;li&gt;  Brought to an end, by a &lt;code&gt;stop()&lt;/code&gt; function&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Having a lifecycle like this, helps in desigining and implementing, a clean, predictable and &lt;em&gt;testable&lt;/em&gt; behaviour.&lt;/p&gt;

&lt;h3&gt;
  
  
  Key observations
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  The dashboard is built as a black-box like entity. It is created, used and destroyed using its APIs. Therefore, some other thread - may be the main thread - is expected to bring it forth and let it go, when done.&lt;/li&gt;
&lt;li&gt;  The dashboard doesn't know how many event producers are alive, at a given point in time. The receiving end is with the dashboard and the sending ends are with the event producers (remember, Sending ends need cloning). So, the dashboard waits till all the sending ends have gone out of existence ( &lt;code&gt;dropped&lt;/code&gt; in Rust parlance), which is when the receiver in Dashboad, returns with an error. This is how the dashboard knows when not to expect any further events.&lt;/li&gt;
&lt;li&gt;  There are more than one channels, Obviously, distributing the sending and receiving ends has to be carefully and correctly done.&lt;/li&gt;
&lt;li&gt;  Receivers cannot be shared between threads, like the way Senders can be. Therefore, to share the receivers, one needs to wrap those in some kind mutually exclusive data structure and then shared. This mutual exclusion is important to ensure that one of the threads accesses it at a given point in time.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>rust</category>
    </item>
    <item>
      <title>Random Rust Notes - 2</title>
      <dc:creator>Nirmalya Sengupta</dc:creator>
      <pubDate>Mon, 17 Apr 2023 16:48:28 +0000</pubDate>
      <link>https://forem.com/nsengupta/random-rust-notes-2-d4n</link>
      <guid>https://forem.com/nsengupta/random-rust-notes-2-d4n</guid>
      <description>&lt;p&gt;[Cover image credit: &lt;a href="https://pixabay.com/users/engin_akyurt-3656355/"&gt;https://pixabay.com/users/engin_akyurt-3656355/&lt;/a&gt;]&lt;/p&gt;

&lt;p&gt;This blog is a collection of notes of key learnings / understandings / Aha moments, as I am kayaking through demanding yet exciting waters, of Rust (#rustlang). If these help someone, I will be happy of course. OTOH, if someone happens to find defects in the code or gaps in my understanding, please correct me. I will remain thankful.&lt;/p&gt;

&lt;p&gt;As a part of a personal project, I am in the middle of learning how to use channels to communicate between two threads. This is quite a common topic. Many people seem to have questions around this topic. Many answers / explanations are available. &lt;/p&gt;

&lt;p&gt;These are my notes, though. &lt;/p&gt;

&lt;h3&gt;
  
  
  Takeaways from the previous note
&lt;/h3&gt;

&lt;p&gt;The previous note is &lt;a href="https://dev.to/nsengupta/random-rust-notes-1-h51"&gt;here&lt;/a&gt; (for a quick recap, in cases needed)&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A channel is created with two ends: one used for sending and other for receiving. While creating a channel, we specify the &lt;strong&gt;type&lt;/strong&gt; of data that will pass through it, when the program runs.&lt;/li&gt;
&lt;li&gt;One thread gets ownership of the end that sends; the other thread gets ownership of the end that receives.&lt;/li&gt;
&lt;li&gt;The channel is always unidirectional, from the sending end to the receiving end. No Request-Response style inter-thread communication is possible, using a single channel.&lt;/li&gt;
&lt;li&gt;Any of the two ends may decide to stop working, &lt;strong&gt;independent&lt;/strong&gt; of the other. No handshaking and &lt;em&gt;Good-Bye&lt;/em&gt; is necessary. The thread that holds the sending end, may decide on its own, if and when to stop sending; similarly, for the thread that holds the receving end. &lt;/li&gt;
&lt;li&gt;If one of the ends becomes non-operational, the other end receives an error. This  behaviour is captured by the return type of &lt;code&gt;send()&lt;/code&gt; and &lt;code&gt;receive()&lt;/code&gt; functions.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  The case of many senders (MPSC)
&lt;/h3&gt;

&lt;p&gt;For those who remember the famous *&lt;em&gt;Producer-Cconsumer *&lt;/em&gt; problem from the textbooks (for me, a few decades ago 😁 ) - here's a &lt;a href="https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem"&gt;wikipedia&lt;/a&gt; page for a quick reference - the mechanism of channels should seem familiar. The thread that sends data into the channel, is the &lt;em&gt;producer&lt;/em&gt; thread; the other thread which reads from the same channel, is the &lt;em&gt;consumer&lt;/em&gt; thread. &lt;/p&gt;

&lt;p&gt;With only two threads, there is one producer and one consumner, commonly referred to as SPSC. What if there are multiple producers, a case of MPSC?&lt;/p&gt;

&lt;p&gt;Obviously, each thread (a producer) has to have access to the sending end of the channel. Put even more simply, every thread has to have a sender for itself.&lt;/p&gt;

&lt;p&gt;Referring to the code snippet in the previous note, we have:&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="c1"&gt;// ... continuing in current thread, let's call it one_thread&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sender&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;receiver&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;channel&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Conversation&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;another_thread&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;  &lt;span class="c1"&gt;// another thread starts here ...&lt;/span&gt;
        &lt;span class="nn"&gt;thread&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;spawn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;move&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="n"&gt;a_message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Conversation&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Hello&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
         &lt;span class="n"&gt;sender&lt;/span&gt;&lt;span class="nf"&gt;.send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a_message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&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_message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Conversation&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;HowAreYou&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
         &lt;span class="n"&gt;sender&lt;/span&gt;&lt;span class="nf"&gt;.send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;another_message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

     &lt;span class="p"&gt;})&lt;/span&gt; &lt;span class="c1"&gt;// another_thread ends here&lt;/span&gt;

     &lt;span class="c1"&gt;// ... continue in one_thread&lt;/span&gt;

     &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;receipt_of_hello&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;receiver&lt;/span&gt;&lt;span class="nf"&gt;.recv&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// message 'Hello' is here&lt;/span&gt;
     &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;receipt_of_how_are_you&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;receiver&lt;/span&gt;&lt;span class="py"&gt;.recv&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// message 'HowAreYou' is here&lt;/span&gt;
     &lt;span class="c1"&gt;// .. go on and do the rest&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because of the &lt;code&gt;move&lt;/code&gt; , the ownership of &lt;code&gt;sender&lt;/code&gt; is transferred to closure above. &lt;code&gt;another_thread&lt;/code&gt; then runs the closure. This easy arrangement is not an option, when there is &lt;code&gt;yet_another_thread&lt;/code&gt;. The ownership of &lt;code&gt;sender&lt;/code&gt; cannot be transferred to the closure for &lt;code&gt;yet_another_thread&lt;/code&gt;, as well. What do we do?&lt;/p&gt;

&lt;p&gt;We simply duplicate the &lt;code&gt;sender&lt;/code&gt; and pass one each to the closures. The above code takes the form:&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="c1"&gt;// ... continuing in current thread, let's call it one_thread&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sender&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;receiver&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;channel&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Conversation&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;another_sender&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sender&lt;/span&gt;&lt;span class="nf"&gt;.clone&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_thread&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;  &lt;span class="c1"&gt;// another thread starts here ...&lt;/span&gt;
        &lt;span class="nn"&gt;thread&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;spawn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;move&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="n"&gt;a_message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Conversation&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Hello&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
         &lt;span class="n"&gt;another_sender&lt;/span&gt;&lt;span class="nf"&gt;.send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a_message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&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_message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Conversation&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;HowAreYou&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
         &lt;span class="n"&gt;sender&lt;/span&gt;&lt;span class="nf"&gt;.send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;another_message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

     &lt;span class="p"&gt;})&lt;/span&gt; &lt;span class="c1"&gt;// another_thread&lt;/span&gt;

    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;yet_another_sender&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sender&lt;/span&gt;&lt;span class="nf"&gt;.clone&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;yet_another_thread&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;  &lt;span class="c1"&gt;// another thread starts here ...&lt;/span&gt;
        &lt;span class="nn"&gt;thread&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;spawn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;move&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="n"&gt;a_message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Conversation&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Hello&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
         &lt;span class="n"&gt;yet_another_sender&lt;/span&gt;&lt;span class="nf"&gt;.send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a_message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&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_message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Conversation&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;HowAreYou&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
         &lt;span class="n"&gt;sender&lt;/span&gt;&lt;span class="nf"&gt;.send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;another_message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

     &lt;span class="p"&gt;})&lt;/span&gt; &lt;span class="c1"&gt;// yet_another_thread&lt;/span&gt;

     &lt;span class="c1"&gt;// ... continue in one_thread&lt;/span&gt;

     &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;receipt_of_hello&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;receiver&lt;/span&gt;&lt;span class="nf"&gt;.recv&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// message 'Hello' is here&lt;/span&gt;
     &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;receipt_of_how_are_you&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;receiver&lt;/span&gt;&lt;span class="py"&gt;.recv&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// message 'HowAreYou' is here&lt;/span&gt;
     &lt;span class="c1"&gt;// .. go on and do the rest&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Obviously, such an arrangement is applicable to more than two producers also. We just need as many duplicates of &lt;code&gt;sender&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;for&lt;/span&gt; &lt;span class="n"&gt;i&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;5&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;  &lt;span class="c1"&gt;// '5' could have been, say '1000'!&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;duplicate_sender&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sender&lt;/span&gt;&lt;span class="nf"&gt;.clone&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

    &lt;span class="c1"&gt;// another thread starts here; we are &lt;/span&gt;
        &lt;span class="nn"&gt;thread&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;spawn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;move&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="n"&gt;a_message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Conversation&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;Hello&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
         &lt;span class="n"&gt;duplicate_sender&lt;/span&gt;&lt;span class="nf"&gt;.send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a_message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&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_message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Conversation&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;HowAreYou&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
         &lt;span class="n"&gt;duplicate_sender&lt;/span&gt;&lt;span class="nf"&gt;.send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;another_message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="nf"&gt;.unwrap&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

     &lt;span class="p"&gt;})&lt;/span&gt; &lt;span class="c1"&gt;// another_thread&lt;/span&gt;

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  Multiple producers done, what about single consumer?
&lt;/h3&gt;

&lt;p&gt;The channel is unidirectional. Producers send messages in the direction of the Consumer. The consumer has to keep waiting for the messages to arrive, until the &lt;code&gt;recv()&lt;/code&gt; returns an error indicating that all producers are done with their action (refer to the previous note). Almost intuitively, a consumer is a loop:&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;while&lt;/span&gt; &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="nf"&gt;Ok&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message_received&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;receiver&lt;/span&gt;&lt;span class="nf"&gt;.recv&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;"Message received: {:?}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="n"&gt;message_received&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;A Rust &lt;a href="https://play.rust-lang.org/?version=stable&amp;amp;mode=debug&amp;amp;edition=2021&amp;amp;gist=b1355cc07240e0af05f20ddf9dbfc729"&gt;playground&lt;/a&gt; is here.&lt;/p&gt;

&lt;p&gt;A crucial understanding is about the &lt;strong&gt;order&lt;/strong&gt; in which the consumer receives the messages. The channel is FIFO for every Producer -&amp;gt; Consumer, but not for all Producers -&amp;gt; Consumer. If producer-1 sends 2 messages (say, m-1-1 and m-1-2) and producer-2 sends 2 messages (say, m-2-1- and m-2-2) to the same consumer, then the order in which the messages reach can be:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  m-1-1, m-2-1-, m-2-2, m-1-2, or&lt;/li&gt;
&lt;li&gt;  m-1-1, m-1-2,  m-2-1, m-2-2 , but &lt;/li&gt;
&lt;li&gt;  m-1-1 always reaches before m-1-2 and m-2-1 always reaches before m-2-2-&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Takeaways
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  Using channels, multiple producers can send messages to a single consumer.&lt;/li&gt;
&lt;li&gt;  Each such producer must have its own copy of the sender-end of the channel. &lt;code&gt;clone&lt;/code&gt; the sender-end for this.&lt;/li&gt;
&lt;li&gt;  Channels are unidirectional and FIFO in structure; therefore, every producer's messages to the consumer reach in the same order in which they are despatched.&lt;/li&gt;
&lt;li&gt;  Multiple producers' messages may reach in any random order, though.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>rust</category>
    </item>
    <item>
      <title>Random Rust Notes - 1</title>
      <dc:creator>Nirmalya Sengupta</dc:creator>
      <pubDate>Mon, 17 Apr 2023 12:27:00 +0000</pubDate>
      <link>https://forem.com/nsengupta/random-rust-notes-1-h51</link>
      <guid>https://forem.com/nsengupta/random-rust-notes-1-h51</guid>
      <description>&lt;p&gt;[Cover image credit: &lt;a href="https://pixabay.com/users/engin_akyurt-3656355/"&gt;https://pixabay.com/users/engin_akyurt-3656355/&lt;/a&gt;]&lt;/p&gt;

&lt;p&gt;This blog is a collection of notes of key learnings / understandings / &lt;em&gt;Aha&lt;/em&gt; moments, as I am kayaking through demanding yet exciting waters, of Rust (#rustlang). If these help someone, I will be happy of course. OTOH, if someone happens to find defects in the code or gaps in my understanding, please correct me. I will remain thankful.&lt;/p&gt;

&lt;h3&gt;
  
  
  Using channels to communicate between threads
&lt;/h3&gt;

&lt;p&gt;As a part of a personal project, I am in the middle of learning how to use channels to communicate between two threads. This is quite a common topic. Many people seem to have questions around this topic. Many answers / explanations are available. &lt;/p&gt;

&lt;p&gt;These are my notes, though. Here goes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Channels provide mechanism for any two threads to communicate asynchrounously. It is unidirectional in structure and behaviour. Every channel has (at least) a Sender and a Receiver. The names indicate which end of the channel is occupied by which. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If we can set up a channel in such a way, that one thread gets hold of the sending end (in other words, is the Sender) and the other thread gets hold of the receiving end (in other words, is the Receiver), then they can converse.  &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Using &lt;code&gt;std::sync::mpsc&lt;/code&gt; crate, the pattern to create a channel is:&lt;br&gt;
    &lt;code&gt;let (sender, receiver) = channel::&amp;lt;Conversation&amp;gt;();&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;  &lt;code&gt;Conversation&lt;/code&gt; is an enum. The messages that are sent over the channel, are of type &lt;code&gt;Conversation&lt;/code&gt;. Almost every example I have come across on the 'Net, uses &lt;code&gt;i32&lt;/code&gt; or &lt;code&gt;&amp;amp;str&lt;/code&gt;, but such an enum is contextually more meaningful (in my view 😁 ). Thus, the name.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;In keeping with the norms followed in tramission of signals, senders are named as &lt;em&gt;tx&lt;/em&gt; and receivers, as &lt;em&gt;rx&lt;/em&gt;. Many blogs/dicsussions use these. Doesn't matter, does it? &lt;em&gt;tx == sender&lt;/em&gt; and &lt;em&gt;rx == receiver&lt;/em&gt;!&lt;/li&gt;
&lt;li&gt;Two threads are going to converse. Therefore, one thread has to have access to the &lt;code&gt;sender&lt;/code&gt; and the other thread, obviously, gets the &lt;code&gt;receiver&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Channels are unidirectional
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;A channel is unidirectional: the messages &lt;em&gt;always&lt;/em&gt; go from the sending side to the receiving side. In other words, the thread holding the &lt;code&gt;sender&lt;/code&gt;, begins the conversation by sending a message; the thread holding the &lt;code&gt;receiver&lt;/code&gt;, takes action on the receipt of the message.&lt;/li&gt;
&lt;li&gt;A key understanding is that the receiver does not respond to the message through the same channel. These channels are not bi-directional and hence, cannot be used for a Request-Response model.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  How do two threads make use of the channel?
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  Create the channel first. Now, we have the &lt;code&gt;sender&lt;/code&gt; and the &lt;code&gt;receiver&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  The act of creation must happen on some thread. After all, we are executing a piece of code, on some existing thread!
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    // ... continuing in current thread, let's call it one_thread
    let (sender, receiver) = channel::&amp;lt;Conversation&amp;gt;();

    let another_thread =  // another thread starts here ...
        thread::spawn(move || { 
         let a_message = Conversation::Hello;
         sender.send(a_message).unwrap();

         let another_message = Conversation::HowAreYou;
         sender.send(another_message).unwrap();

     }) // another_thread ends here

     // ... continue in one_thread

     let receipt_of_hello = receiver.recv().unwrap(); // message 'Hello' is here
     let receipt_of_how_are_you = receiver.recv.unwrap(); // message 'HowAreYou' is here
     // .. go on and do the rest
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;  The &lt;strong&gt;order&lt;/strong&gt; in which another_thread is sending the messages, is the &lt;strong&gt;order&lt;/strong&gt; in which the receiver is receiving them. This is because the channel is &lt;strong&gt;FIFO&lt;/strong&gt; in structure and behaviour. This is an important observation, because what if there are more than one senders? More about it later.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  How do threads know when to stop?
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  An ongoing conversation stops, when one of the participants stops. Therefore, if either the Sender stops or the Receiver stops, the other side must have to know. This is important to understand.&lt;/li&gt;
&lt;li&gt;  Significantly, neither of  &lt;code&gt;std::sync::mpsc::{Receiver,Sender}&lt;/code&gt; provides any mechanism to &lt;em&gt;stop&lt;/em&gt; sending or receiving. But, they are &lt;em&gt;dropped&lt;/em&gt;, meaning they cease to exist, perhaps because the scope in which they are defined, comes to an end.&lt;/li&gt;
&lt;li&gt;  We note that the sending side (&lt;code&gt;one_thread&lt;/code&gt; above) and the receiving side (&lt;code&gt;another_thread&lt;/code&gt; above) are completely disconnected (naturally, one argues, because they are threads). Neither of the two is aware of the continued existence of the other side. Unless the channel through which they are communicating offers help!&lt;/li&gt;
&lt;li&gt;  To help, the channel specifies this: if a sender fails to send - in other words, the act of sending returns with an error - the sender comes to know that the receiver has become non-existent (no point sending any more). Similarly, if the sender goes out existence (viz. being &lt;em&gt;dropped&lt;/em&gt; perhaps), the receiver is handed an error (nothing is going to arrive any further). Based on this, the threads can decide how to deal with a disconnection from one another.&lt;/li&gt;
&lt;li&gt;  Because the action of send/receive may return with an error, the retrun type of of these functions is a &lt;code&gt;Result&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;  A call to send() returns a &lt;code&gt;Result&amp;lt;(),SendError&amp;gt;&lt;/code&gt;. A call to receive() returns a &lt;code&gt;Result&amp;lt;Conversation,RecvError&amp;gt;&lt;/code&gt; . Of course, that &lt;code&gt;Conversation&lt;/code&gt; is my example type. It can be any valid type (generically speaking, &lt;code&gt;Result&amp;lt;T,RecvError&amp;gt;&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;   This &lt;code&gt;Result&amp;lt;..&amp;gt;&lt;/code&gt; explains the use of &lt;code&gt;unwrap()&lt;/code&gt; in the code snippet, above.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Takeaways
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;A channel is created with two ends: one used for sending and other for receiving. While creating a channel, we specify the &lt;strong&gt;type&lt;/strong&gt; of data that will pass through it, when the program runs.&lt;/li&gt;
&lt;li&gt;One thread gets ownership of the end that sends; the other thread gets ownership of the end that receives.&lt;/li&gt;
&lt;li&gt;The channel is always unidirectional, from the sending end to the receiving end. No Request-Response style inter-thread communication is possible, using a single channel.&lt;/li&gt;
&lt;li&gt;Any of the two ends may decide to stop working, &lt;strong&gt;independent&lt;/strong&gt; of the other. No handshaking and &lt;em&gt;Good-Bye&lt;/em&gt; is necessary. The thread that holds the sending end, may decide on its own, if and when to stop sending; similarly, for the thread that holds the receving end. &lt;/li&gt;
&lt;li&gt;If one of the ends becomes non-operational, the other end receives an error. This  behaviour is captured by the return type of &lt;code&gt;send()&lt;/code&gt; and &lt;code&gt;recv()&lt;/code&gt; functions.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>rust</category>
    </item>
    <item>
      <title>Why am I learning Rust?</title>
      <dc:creator>Nirmalya Sengupta</dc:creator>
      <pubDate>Tue, 04 Apr 2023 07:00:00 +0000</pubDate>
      <link>https://forem.com/nsengupta/why-am-i-learning-rust-57fe</link>
      <guid>https://forem.com/nsengupta/why-am-i-learning-rust-57fe</guid>
      <description>&lt;h3&gt;
  
  
  The Build-up
&lt;/h3&gt;

&lt;p&gt;I met Debasis Basu (&lt;a href="https://www.linkedin.com/in/debasis-basu-1501056/"&gt;LinkedIn&lt;/a&gt;) at a social event, a few weeks ago.&lt;/p&gt;

&lt;p&gt;Debasis is a childhood friend. We studied at the same residential high-school and spent six of our formative years together: a brilliant student (much better than I have been 😁) and an excellent sportsperson (again, much ahead of me 😞), Debasis has had an outstanding career for over 35 years, after graduating from IIT, Kharagpur, India. A keen observer of the goings-on, in the technology industry, Debasis has this habit of putting me off-guard, by asking relevant, pointed and interesting questions. I fumble but then, I become aware of gaps between what I know and what I &lt;em&gt;think&lt;/em&gt; I know.&lt;/p&gt;

&lt;p&gt;This time, too, Debasis threw a seemingly simple question at me: why are you learning Rust? What is it that you can do using Rust, that you cannot do using say, 'C'?&lt;/p&gt;

&lt;p&gt;I put up a brave face, thought on my feet and mumbled something. It quickly became obvious to me, that my effort did not leave any much effect on him. He looked plainly unimpressed.&lt;/p&gt;

&lt;p&gt;Later, I played the conversation in my mind. If I could not tell Debasis - who has (more than) the requisite background and was genuinely all ears - reasonably convincingly why I was learning Rust, what chance did I have to tell someone else, having much less attention to and much less time for, what I had to say? More importantly, did I ever tell myself why would I like to learn Rust?&lt;/p&gt;

&lt;p&gt;So, I decided to put together my thoughts into a more coherent form, but I will begin with a quote I have remained very, very fond of:&lt;/p&gt;




&lt;p&gt;A language that doesn't affect the way you think about programming, is not worth knowing.&lt;/p&gt;

&lt;p&gt;-- Alan Perlis&lt;/p&gt;




&lt;h3&gt;
  
  
  Learning a new language makes me think differently from what I am used to
&lt;/h3&gt;

&lt;p&gt;Rust is a systems programming language. I have developed non-trivial software using 'C' in the first decade and a half of my career. That was my first - and so far, last - fortuitous association with what is called &lt;em&gt;systems programming&lt;/em&gt;. A compact language, having 32 keywords, 'C' propounded a philosophy of doing a lot by saying a little. Being a &lt;em&gt;low_level&lt;/em&gt; language, it provided powerful constructs that allowed me - the programmer - to go very near to the world where the &lt;em&gt;machine&lt;/em&gt; ruled. The fall-out was a huge responsibility on me to be 'right' along the entire flow from very near to the user application to very near to the machine. The price to pay for being inattentive could be disatrous. The power was intoxicating for a programmer and the responsibility was unnerving. The long nights spent in following a wayward pointer are still etched in my mind.&lt;/p&gt;

&lt;p&gt;Rust brings in a different philosophy. The Rust compiler has strict rules and it employs them ruthlessly. Armed with these rules, it tries to foresee where my code can go wrong &lt;em&gt;when it runs&lt;/em&gt;, &lt;strong&gt;even when I haven't been careful&lt;/strong&gt;. This changes the game altogether. The compiler can see what I - the programmer - have possibly failed to see and then, by throwing compile-time errors, the compiler refuses to let me move ahead. Thus, to satisfy the compiler, I am forced to consider implications of my code while writing it:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;is a variable associated with right data type througout its usage?&lt;/li&gt;
&lt;li&gt;is a pointer dangling dangerously?&lt;/li&gt;
&lt;li&gt;is a piece of memory being used incautiously by two threads? 
and such.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The important point is that the compiler doesn't let me proceed with such vulnerabilities. Consequently, in order to run my program, I have to think the way the compiler is thinking. This forced co-thinking with a very smart and powerful compiler has its benefits: I am made to think more precisely than I am used to. It helps sharpen my programming thinking.&lt;/p&gt;

&lt;h3&gt;
  
  
  I feel welcome. Yes, that matters.
&lt;/h3&gt;

&lt;p&gt;From the very first time I stepped in the world of Rust, I felt that folks in the community were all extending a helping hand. &lt;a href="https://doc.rust-lang.org/stable/book/"&gt;Documentations&lt;/a&gt; were crisp and clear. Tutorials were meant to &lt;em&gt;coach&lt;/em&gt; me and not just to take me to quick end of an example. Exercises were usefully graded, with appropriate hints to assist. Videos (on youtube) varied from simple features to complex concepts, without being patronizing.&lt;/p&gt;

&lt;p&gt;Now, one may raise the eyebrow and wonder how do all these make Rust special? Are proponents and practitioners of other, newer languages any different?&lt;/p&gt;

&lt;p&gt;Well, I will be honest. I cannot knowledgeably comment on how is the state of affairs with long list of other languages. I know and professionally work (have worked) with a few of them. I have dabbled with a couple of others. Thus, the background with which I say this, is quite limited.&lt;/p&gt;

&lt;p&gt;It is not that I decided to jump into Rust without any consideration. I had been watching Rust from the fence for some time. I have spent time watching video clips, listening to podcasts and of course, reading blogs as well as discussion-threads in 'Stackoverflow' and 'reddit'. Like I mentioned earlier, Rust indeed has many quirks, some of which are quite inscrutable at the beginning. At times, this is definitely frustrating.&lt;/p&gt;

&lt;p&gt;Countless enthusiastic newbies like me threw (and are throwing) in questions, ranging from eye-opener-types to eye-rolling-in-socket-types. However, I didn't find responses which were dismissive in nature and in tone. One may argue that the sample-set is too small, but I did sense the care and the wardship of the Rust experts who proffered their responses. It was as if they knew that the language brought in approaches which, a large swath of mainstream programmers hadn't heard about, let alone being comfortable. These programmers needed calming hands on their shoulders while they joined the community.&lt;/p&gt;

&lt;h3&gt;
  
  
  Praising by practitioners, backing by biggies
&lt;/h3&gt;

&lt;p&gt;Even though large corporations of the world of software are not particularly loved for their large-heartedness 😉, it is undeniable that their endorsement of a technology matters. A programming language's uptake gets a shot in the arm, when they announce their support, contribute to the effort and in the process, keep generations of programmers enthused. &lt;em&gt;Java&lt;/em&gt;, &lt;em&gt;Javascript&lt;/em&gt; (nodeJS to be a little more accurate), &lt;em&gt;Swift&lt;/em&gt; etc. good examples.&lt;/p&gt;

&lt;p&gt;Rust has made some of the biggies interested and that is a good news. Amazon,, Microsoft and Cloudflare have endorsed it and have put up production versions of some of their &lt;a href=""&gt;offerings&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Several publicly available datasets indicate that Rust has a significant following and the trend doesn't seem to wane.&lt;/p&gt;

&lt;p&gt;TIOBE &lt;a href="%5BTIOBE%20Index%20-%20TIOBE%5D(https://www.tiobe.com/tiobe-index/)"&gt;Index&lt;/a&gt; confirms the upward trend, but Rust decidedly has a long distance to cover.&lt;/p&gt;

&lt;p&gt;Redmonk &lt;a href="%5BThe%20RedMonk%20Programming%20Language%20Rankings:%20June%202022%20%E2%80%93%20tecosystems%5D(https://redmonk.com/sogrady/2022/10/20/language-rankings-6-22/)"&gt;suggests&lt;/a&gt; in its June'2022 report that "it seems increasingly clear that the hypothesis of a temporary equilibrium of programming language usage is supported by the evidence". If this indeed is the case, Rust has a steep upwards climb ahead, from its current position of 19 out of 20.&lt;/p&gt;

&lt;p&gt;According to &lt;a href="%5BTop%20Computer%20Languages%202022%20-%20StatisticsTimes.com%5D(https://statisticstimes.com/tech/top-computer-languages.php)"&gt;statisticstimes.com&lt;/a&gt;, Rust is showing slow yet steady progress upwards in popularity in countries like US, Germany, France, UK and in &lt;strong&gt;India&lt;/strong&gt;!&lt;/p&gt;

&lt;p&gt;So, there's something going on with Rust. Will it sustain (or accelerate) its current rate of adoption? Time will tell.&lt;/p&gt;

&lt;h3&gt;
  
  
  So, where do I find myself?
&lt;/h3&gt;

&lt;p&gt;Well, I am not a soothsayer. I cannot and certainly don't want to, predict the fate of Rust. I feel that Rust very unlikely to dethrone Python or Javascript based on number of deployed applications. It is also unlikely to challenge Java (and other JVM based languages) for enterprise-focused, large, server-side application, meaningfully. It will possibly remain a niche language, used for specific purposes and by a smaller segment of the tech-industry. Having said that, I also feel that these specific, niche areas will only increase in number. Hopefully, the time and effort that I am investing in learning and mastering Rust, will not go in vain.&lt;/p&gt;

&lt;p&gt;So, this is all that I have to say to Debasis 🤗.&lt;/p&gt;

&lt;p&gt;I have steadfastly kept away from the technical features of Rust, their power and their usage-patterns and the cautionary steps which the experts remind the new entrants. Debasis was not interested about those in any case and this blog is primarily meant to give a compact and honest answer to the question he posed, during a sumptuous dinner in Kolkata, India.&lt;/p&gt;

</description>
      <category>rust</category>
    </item>
    <item>
      <title>Product Owners, the Technical debt matters to you too!</title>
      <dc:creator>Nirmalya Sengupta</dc:creator>
      <pubDate>Mon, 02 Jan 2023 13:31:20 +0000</pubDate>
      <link>https://forem.com/nsengupta/product-owners-the-technical-debt-matters-to-you-too-7bm</link>
      <guid>https://forem.com/nsengupta/product-owners-the-technical-debt-matters-to-you-too-7bm</guid>
      <description>&lt;p&gt;Attribution: Cover &lt;a href="https://www.freepik.com/free-vector/businessman-chained-debts_1311554.htm#query=debt&amp;amp;position=0&amp;amp;from_view=keyword"&gt;Image by iconicbestiary&lt;/a&gt; on Freepik&lt;/p&gt;

&lt;h5&gt;
  
  
  TL;DR
&lt;/h5&gt;

&lt;p&gt;Technical Debt, is unavoidable in the life of a successful software. A l-o-t has been (and still being) discussed on this and many have spoken about its nature, the risk it poses and ways to deal with it. However, an overwhelming number of these, explains it from the PoV of the Engineering (or Development) team. Here's my attempt to expound the topic for the Business team: how they should see this inseparable part of software.&lt;/p&gt;

&lt;h4&gt;
  
  
  Preface
&lt;/h4&gt;

&lt;p&gt;The topic of &lt;a href="%5BTechnical%20debt%20-%20Wikipedia%5D(https://en.wikipedia.org/wiki/Technical_debt)"&gt;Technical debt&lt;/a&gt; - colloquially, &lt;strong&gt;Tech-debt&lt;/strong&gt; - is perhaps one of the most common topics that the we, in the business of developing software, love to discuss, if not to embroil ourselves in. In a street-lingo précis, Tech-debt represents a bunch of TODOs in the software that exists in the code, database, configuration, deployment strategy etc. These come into existence primarily because the Business side (Product Owners/Stakeholders/Sponsors) wants the software to be usable soon, and the ENGineering side (Developers/QA/Devops) complies, leaving spots of uncleanliness (software-wise, please) behind, as a show of pragmatism. These spots carry cost (of clean up), which one may or may not want to pay forthwith. This is because, as in a financial debt, carrying a Tech-debt for some benefit &lt;u&gt;now&lt;/u&gt;, and paying the increased technical due &lt;u&gt;later&lt;/u&gt;, may make perfect business sense.&lt;/p&gt;

&lt;p&gt;In general, people agree that such a debt is going to bite as some point in time. But, if it can be absorbed in some way or the other - without having any ruinous effect on the software and therfore, the business - there is nothing really grossly wrong about it. After all, if a stakeholder - who pays for what is being built and going to be used - decides to view it as an unavoidable cost measured against other benefits, there is nothing really to complain.&lt;/p&gt;

&lt;p&gt;Myriads of friendly discussions, verbal fisticuffs, compelling presentations, persuasive video-clips and serious research on the topic later, why do I write about this topic again? More to the point, is there anything that I am going to add to it, really?&lt;/p&gt;

&lt;p&gt;Well, a very large proportion of the available materials on Tech-debt treats the subject from the development team's side. My intention is to bring to the &lt;strong&gt;Product owners&lt;/strong&gt;, &lt;strong&gt;Stakeholders&lt;/strong&gt;, or Sponsors, the aspect of Tech-debt and the cost associated with it! It is my considered opinion that those who put in money to have the software built and then sell, &lt;strong&gt;must understand&lt;/strong&gt; where and how, the debt hurts. I am addressing them in second person, in this blog. It is &lt;strong&gt;their attention that I am drawing&lt;/strong&gt;, in this article.&lt;/p&gt;




&lt;p&gt;Note: I am not to going elaborate on what is Technical debt, how does a piece of software accrue this unavoidable yet unwelcome payable and how is a DEV team supposed to deal with it. Tons of very good materials reside on the 'Net which explain, elaborate and exemplify these aspects. If you are interested to know first-hand or know more, I have included a links to a bunch at the end of this article.&lt;/p&gt;




&lt;h5&gt;
  
  
  The murmur
&lt;/h5&gt;

&lt;p&gt;To begin with, trust your DEV team; especially the seniors. They are much likely to sense when things are gradually becoming difficult to ignore. If they are mentioning this in discussions and reviews, pay attention.&lt;/p&gt;

&lt;p&gt;To be fair, any dyed-in-the-wool software developer, feels very happy to see a &lt;em&gt;well-built&lt;/em&gt; software being shipped and used. That an user (internal or external) finds the software useful, is what developers love to hear. There is perhaps no better incentive than this.&lt;/p&gt;

&lt;p&gt;When a growing Tech-debt is discomfiting them, and they are expressing it, take that as a good sign. What they are telling you, is that they &lt;em&gt;care for what they are building&lt;/em&gt; and that is what you want to be built. Your inattention can be taken in as your disregard for the quality of what you are paying for. The developers can see through this very quickly. And, after some time, they will begin to care less for what they build. The fallout will be borne by you and your users.&lt;/p&gt;




&lt;p&gt;This [report ](&lt;a href="https://www.mckinsey.com/capabilities/mckinsey-digital/our-insights/tech-debt-reclaiming-tech-equity"&gt;Tech debt: Reclaiming tech equity | McKinsey&lt;/a&gt; from year 2020, from &lt;em&gt;McKinsey &amp;amp; Company&lt;/em&gt;, says that CIOs believe that Tech-debt is increasing and a vast majority of them spend less than 20% of their budget to stave it off.&lt;/p&gt;




&lt;h5&gt;
  
  
  The velocity
&lt;/h5&gt;

&lt;p&gt;As your paying customers increase in number, they expect predictable behaviour from the software. At the same time, your sales team acquires new customers too. While existing and popular features cannot falter, new features have to be added as well. The balance is crucial. More often than not, the velocity is measured by number of features shipped. However, if the software has been built keeping N simultaneous users in mind, to keep it running for N + m users, requires work, even if - for argument's sake - &lt;strong&gt;no new feature is added&lt;/strong&gt;. Perhaps the Customer Support team is engaged with the ENG team, in the very useful and necessary effort to settle the new users. Perhaps your Business Analytics team is asking for some set of data, unavailable so far and the ENG team is busy preparing for it. The &lt;em&gt;reduced velocity&lt;/em&gt; - meaning, new features are not rolling out as rapidly as you expect - doesn't mean that the ENG team is sluggish. On the contrary, they are helping the business be in the current, &lt;u&gt;steady&lt;/u&gt; state. Under the hood, they are taking considerable effort to keep the Tech-debt as low as possible. It is worthwhile for you to bear in mind, that even though the Business sees slower newer features, the business assumes no brittleness in the existing features either. And, latter consumes what is called your ENG team's bandwidth. That, in turn, affects velocity.&lt;/p&gt;

&lt;h5&gt;
  
  
  The Internal quality
&lt;/h5&gt;

&lt;p&gt;Users judge the quality of a software primarily by the outward manifestation of it: ease of use, intuitiveness, completeness etc. These form the &lt;em&gt;external quality&lt;/em&gt; of the software and bring in and/or retain paying customers. However, how well the software deals with further, upcoming and inevitable changes depends on its &lt;em&gt;internal quality&lt;/em&gt;. In plain terms, the internal quality is the property which determines the velocity (see above); for example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;How quickly are customer-support issues resolved (remember, this may mean a release, a GA if you like, is faltering)?&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How easily can 3rd party software be integrated (remember, not all inputs to the software will come through an web-page and your business' organic expansion may depend on ease of such integrations)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How frequently are released versions reported back with something broken (remember, the older the broken behaviour is, the higher is the cost of fixing it)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How frequently are main DB (Tables / Collections / Documents etc.) modified for implementing quick changes or fixes?&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How long does it take for new entrants in the team to get going&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;etc.&lt;/p&gt;

&lt;p&gt;The larger the unpaid Tech-debt, the higher is the chance that the software's internal quality is compromised. It is in the interest of the business to help keep the level of internal quality, high.&lt;/p&gt;

&lt;p&gt;Martin Fowler - in his signature lucid style - has &lt;a href="%5BIs%20High%20Quality%20Software%20Worth%20the%20Cost?%5D(https://martinfowler.com/articles/is-quality-worth-cost.html)"&gt;written&lt;/a&gt; about the &lt;em&gt;internal quality&lt;/em&gt; and its implications on the cost of software. If you are a sponsor of non-trivial, money-earning software, I encourage you to read it; especially the point of &lt;em&gt;cruft&lt;/em&gt;_ which according to me, soon becomes a &lt;em&gt;sludge&lt;/em&gt;, if left unattended for too long.&lt;/p&gt;

&lt;h5&gt;
  
  
  The Roadmap
&lt;/h5&gt;

&lt;p&gt;The Roadmap lays out the plan of gradual transformation of the software being built, in keeping with what the Business needs. Almost always (in my experience), the milestones along these roadmaps, tend to focus on the newer things: everyone wants to watch the software flourish (what is a better word here?). Objectively speaking, there is nothing wrong with that view, but it is incorrect - and provenly detrimental in the longer run - to overlook the importance of consolidation of the internals of the software, before and while, we march forward. The DEV team is in the best position to have a sense of extent of (a) necessary consolidation and (b) the effort to undertake that.&lt;/p&gt;

&lt;p&gt;As an aside, the roadmap is liable to change any time, for a number of reasons. Like &lt;a href="https://www.linkedin.com/in/kevlin/"&gt;Kevlin Henney&lt;/a&gt; so pithily says in &lt;a href="https://www.infoq.com/presentations/six-impossible-things/"&gt;Six Impossible Things&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If I only have one road, I don't really need a roadmap.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Think of it this way: if the product's roadmap is susceptible to unforeseen changes in the prevailing business condition, then the structure behind the software is susceptible to unforeseen changes in the roadmap too. The question is how well can the existing version absorb these changes, without any adverse aftermath. This is where the quality of the software matters: the lesser the accumulated Tech-debt, the more is the inner resilience. And, of course, the level of craftsmanship of your DEV team is a very important factor too.&lt;/p&gt;

&lt;h5&gt;
  
  
  The cost
&lt;/h5&gt;

&lt;p&gt;That an useful software - meaning, in this case, having happy and paying users - is going to &lt;em&gt;evolve&lt;/em&gt; is a well-known tenet in the world of software programming. In fact, the demand to evolve is an indication that the software is doing well and that, your business is benefited by it. A steadily evolving software is a result of not only great and appropriate design (&lt;em&gt;high quality&lt;/em&gt;, refer above) but also - and, this is important - better understanding of how is it supposed to work. As your Business team is understanding the prevailing and upcoming environment better, your ENG team &lt;em&gt;too&lt;/em&gt;, is understanding what must be done, undone and redone, better. The act and benefit of discovery are applicable equally to both the teams. The Business team decides what additions and modifications must be done to the software, and the ENG team:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Realizes what should have been done in the past&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Confirms what should be done now, and&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Suspends what will have to be done later&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;to the software.&lt;/p&gt;

&lt;p&gt;(2) is what the Business team is interested in, because while it carries a cost (time and effort) , it also offers immediate benefit (better features, happier users, more business). The ENG team, however, has to decide the extent of necessary reparative measures (ENG Team loves to refer to this as Refactoring) owing to (1) as well as how much should be left for (3). What is important for you to understand is this:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Things that ENG team decides &lt;em&gt;not to do&lt;/em&gt; now, add to the Tech-debt&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;For every successive (3), the debt mounts&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The truth is that some Tech-debt will always remain in a live, useful and continually changing software, and not all of them will be (should be) serviced perhaps. However, what must not escape your radar as the Product owner / Stakeholder / Sponsor, is that the accumulating debt should not reach a level where servicing the debt is a Sisyphean task, economically speaking. Both the velocity and quality will suffer.&lt;/p&gt;

&lt;h5&gt;
  
  
  The team
&lt;/h5&gt;

&lt;p&gt;Professional and sincere software programmers (your ENG team is comprised of them), want to do a good job. They tend to leave code in a better shape than it had been in the past (&lt;a href="%5B8.%20The%20Boy%20Scout%20Rule%20-%2097%20Things%20Every%20Programmer%20Should%20Know%20%5BBook%5D%5D(https://www.oreilly.com/library/view/97-things-every/9780596809515/ch08.html)"&gt;Boy scout rule&lt;/a&gt;). This is their craft and they take pride in it. Mounting Tech-debt and woes originating from organisational disregard of it, affects their productivity and morale, and dents their pride. The quality of the software suffers, inevitably and worse, silently. A survey made by &lt;a href="https://www.stepsize.com/"&gt;Stepsize&lt;/a&gt; in 2021 reveals that 52% of developers believe that Tech-debt &lt;strong&gt;negatively impacts a team's morale&lt;/strong&gt; and 66% believe that they would &lt;strong&gt;ship 100% faster&lt;/strong&gt; if they had a process for servicing the debt.&lt;/p&gt;

&lt;p&gt;There is another aspect that needs a mention. New joinees in the ENG team get going faster if the software (including primary codebase, scripts, database schema, documentation, automated tests etc.) carry less Tech-debt. Much of the Tech-debt are left as assumptions, generally shared amongst the members of the team. People leaving ENG team is a regular affair. A software with much reduce Tech-debt has much less chance of being orphaned.&lt;/p&gt;




&lt;p&gt;I am a software programmer with ~3 decades of experience, having learnt through many successes I have influenced or caused, and many failures and mistakes I have made. I &lt;a href="https://www.linkedin.com/in/nirmalyasengupta/"&gt;work&lt;/a&gt; as a platform technologist with a consortium of consultants: &lt;a href="https://www.linkedin.com/company/swanspeed-consulting/about/"&gt;Swanspeed Consulting&lt;/a&gt;.&lt;/p&gt;




&lt;h3&gt;
  
  
  More reading:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Martin Fowler's &lt;a href="%5BTechnicalDebt%5D(https://martinfowler.com/bliki/TechnicalDebt.html)"&gt;blog&lt;/a&gt; on Technical debt (revised in 2019):&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Ben 'Hosk' on why programmers develop &lt;a href="https://medium.com/javascript-in-plain-english/why-do-developers-create-low-quality-code-and-Tech-nical-debt-because-they-are-rewarded-for-it-76d4714dcef6"&gt;low-quality&lt;/a&gt; code?&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;On the topic of a quick &lt;a href="https://medium.com/@amir_hTech-h-debt-to-cost-3fcec6ec62dc"&gt;calculation&lt;/a&gt; of Technical debt&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Tech-debt is &lt;a href="%5BHow%20Does%20Technical%20Debt%20Affect%20a%20Business%20Financially?%20%7C%20Toptal%5D(https://www.toptal.com/finance/part-time-cfos/technical-debt)"&gt;seen&lt;/a&gt; through the lens of FinDebt&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Raja &lt;a href="https://www.linkedin.com/in/nagkumar/"&gt;Nagendra Kumar&lt;/a&gt;, on the topic of 'DONE' on &lt;a&gt;LinkedIn&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;An useful ready-reckoner of 'Technical Debt' from &lt;a href="%5BTechnical%20Debt%20Handbook%20for%20modern%20engineering%20teams%5D(https://www.stepsize.com/handbook/)"&gt;Stepsize&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>techdebt</category>
    </item>
    <item>
      <title>Digital Clock using Rust (toy project)</title>
      <dc:creator>Nirmalya Sengupta</dc:creator>
      <pubDate>Thu, 15 Dec 2022 16:01:48 +0000</pubDate>
      <link>https://forem.com/nsengupta/digital-clock-using-rust-toy-project-4j6i</link>
      <guid>https://forem.com/nsengupta/digital-clock-using-rust-toy-project-4j6i</guid>
      <description>&lt;p&gt;Attribution: Cover image by &lt;a href="https://www.freepik.com/free-vector/watch_3099029.htm#query=digital%20alarm%20clock&amp;amp;position=5&amp;amp;from_view=keyword" rel="noopener noreferrer"&gt;Image by rawpixel.com&lt;/a&gt; on Freepik&lt;/p&gt;

&lt;p&gt;I am a Rust newbie. Like many other Rust (#rustlang) learners, I am also cutting my teeth on the language by paging through the Rust book (&lt;a href="https://doc.rust-lang.org/edition-guide/rust-2021/index.html/" rel="noopener noreferrer"&gt;Link&lt;/a&gt;) and the one from Oreilly (&lt;a href="https://www.oreilly.com/library/view/programming-rust-2nd/9781492052586/" rel="noopener noreferrer"&gt;Link&lt;/a&gt;), solving small puzzles, writing code snippets, and rummaging through a host of helpful blog-posts, as well as questions/answers on &lt;em&gt;Stackoverflow&lt;/em&gt; and Rust users' group (&lt;a href="https://users.rust-lang.org/" rel="noopener noreferrer"&gt;Link&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;On one such evening, while wandering through Youtube, I had come across this particular video (&lt;a href="https://www.youtube.com/watch?v=gX6EFBICIcY" rel="noopener noreferrer"&gt;Link&lt;/a&gt;) by (&lt;a href="https://www.youtube.com/@andythomason8112" rel="noopener noreferrer"&gt;Andy Thomason&lt;/a&gt;). In the video, Andy codes online, and takes us through a small application which brings up a digital clock on the screen. I found that quite interesting, especially the way he modeled the arms of the digits (&lt;a href="https://github.com/simple-rust-projects/simple-rust-clock" rel="noopener noreferrer"&gt;code is here&lt;/a&gt;). The code was wonderfully concise and posed no problem for a newbie like me to follow.&lt;/p&gt;

&lt;p&gt;I thought I will take this idea further, primarily to strengthen my Rust skills. My intention has been to emulate a few things while writing this toy application:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;To model a 7-Led BCD decoder for each digit&lt;/li&gt;
&lt;li&gt;To use special ASCII characters to represent each Led  and adopt ANSI Escape Sequences for cursor positioning and drawing on a text - xterm, in my case - terminal (note: Andy did the same, I just followed his footsteps)&lt;/li&gt;
&lt;li&gt;To behave as if the clock's ticks are coming in as external signals, as opposed to sleeping between two successive calls to get current time&lt;/li&gt;
&lt;li&gt;To trap a CTRL-C command (that stops the application) and ensure that the cursor is back to its regular blinking behaviour&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;Note: Let me repeat that all the above are &lt;em&gt;emulations&lt;/em&gt;, an attempt to highlight the core behaviour; no hardware is interfaced with the toy application I have written.&lt;/p&gt;




&lt;h4&gt;
  
  
  BCD for each digit
&lt;/h4&gt;

&lt;p&gt;For a realistic clock ( &lt;strong&gt;HH:MM:SS&lt;/strong&gt; ) to appear on the screen, 6 digits are needed, namely H, H, M, M, S, S. Each of these digits is supposed to be a 7-segment display unit.&lt;/p&gt;

&lt;p&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%2F2oi64rzx8a42zvninrp3.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%2F2oi64rzx8a42zvninrp3.png" alt="Typical 7-segment display electronic unit"&gt;&lt;/a&gt;&lt;br&gt;
(Source: &lt;a href="https://en.wikipedia.org/wiki/Seven-segment_display" rel="noopener noreferrer"&gt;https://en.wikipedia.org/wiki/Seven-segment_display&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;For a digit to be visible, several of these segments - also called LEDs (or LCDs) - should glow and other should remain unlit. The LEDs are numbered - &lt;em&gt;lettered&lt;/em&gt;, to be more accurate - thus:&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%2Futximg6ywhrzxlbh50yl.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%2Futximg6ywhrzxlbh50yl.png" alt="Enumerated 7 LEDs"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Source: &lt;a href="https://en.wikipedia.org/wiki/Seven-segment_display" rel="noopener noreferrer"&gt;https://en.wikipedia.org/wiki/Seven-segment_display&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Each digit can be one of the 10 values, namely '0' to '9'. For example, for displaying digits '6', '0' and '2', the LEDs should light up as below:&lt;/p&gt;

&lt;p&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%2Fi0curiayz8724zo3yl20.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%2Fi0curiayz8724zo3yl20.png" alt="Lit and unlit LEDs"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Source: &lt;a href="https://www.electricaltechnology.org/2018/05/bcd-to-7-segment-display-decoder.html" rel="noopener noreferrer"&gt;https://www.electricaltechnology.org/2018/05/bcd-to-7-segment-display-decoder.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The following table shows, the input signal combinations vs the corresponding LED-borne digits:&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%2Fs0bfejp9hirvkd9d9bbt.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%2Fs0bfejp9hirvkd9d9bbt.png" alt="Truth Table for 3 digits"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The point is that using a 4-bit input set - referred to as &lt;strong&gt;B&lt;/strong&gt;inary &lt;strong&gt;C&lt;/strong&gt;oded &lt;strong&gt;D&lt;/strong&gt;ecimals (BCD) - all the 10 digits can be displayed. (the truth-table is in the README).&lt;/p&gt;

&lt;p&gt;I have modeled:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;every LED as a &lt;em&gt;struct&lt;/em&gt; :
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight rust"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Datatype that captures a Led&lt;/span&gt;
&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;Led&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;show_character&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;hide_character&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt; &lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;light_status&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;bool&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;on_receiving_next_signal&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nb"&gt;u8&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;bool&lt;/span&gt; &lt;span class="c1"&gt;// Closure that evaluates a BCD-signal, before deciding what the light_status should become&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;A BCD signal as an &lt;code&gt;u8&lt;/code&gt; (unsigned 8-bit):
&lt;/li&gt;
&lt;/ul&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="nf"&gt;Nibbles&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="nb"&gt;u8&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The 4 most-significant-bits (MSB) of this &lt;em&gt;u8&lt;/em&gt; are ignored always and the 4 least-significant-bits (LSB) represent the BCD for each of 10 digits. Moreover, 4 LSB combinations which represent values '10' to '15' are ignored as well (the truth-table is in the README).&lt;/p&gt;
&lt;h5&gt;
  
  
  Logic to determine if the LED should be lit
&lt;/h5&gt;

&lt;p&gt;Using Karnaugh Map, the minimal boolean signal combination is arrived at, for every LED. For example, based on the table above, the boolean logic that leads to a lit or unlit LED 'a' is 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;const&lt;/span&gt; &lt;span class="n"&gt;LED_A_GATE_LOGIC&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nb"&gt;u8&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;bool&lt;/span&gt; &lt;span class="o"&gt;=&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="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nb"&gt;u8&lt;/span&gt; &lt;span class="p"&gt;|&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// 8-bits and BCD (MSBs start from leftmost)&lt;/span&gt;
    &lt;span class="c1"&gt;// 0       0       0       0       A       B      C      D&lt;/span&gt;
    &lt;span class="c1"&gt;// Using karnaugh Map and don't care conditions: A + C + B.D + ~B.~D&lt;/span&gt;

    &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;input&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="mi"&gt;0b00001000&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0x08&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;              &lt;span class="c1"&gt;// *nibble_a == 1u8&lt;/span&gt;
        &lt;span class="p"&gt;||&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;input&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="mi"&gt;0b00000010&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0x02&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;       &lt;span class="c1"&gt;// *nibble_c == 1u8&lt;/span&gt;
        &lt;span class="p"&gt;||&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;input&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="mi"&gt;0b00000101&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0x05&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;       &lt;span class="c1"&gt;// (*nibble_b == 1u8 &amp;amp;&amp;amp; *nibble_d == 1u8)&lt;/span&gt;
        &lt;span class="p"&gt;||&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;input&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt; &lt;span class="mi"&gt;0b00000101&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt;  &lt;span class="mi"&gt;0x00&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;      &lt;span class="c1"&gt;// (*nibble_b == 0u8 &amp;amp;&amp;amp; *nibble_d == 0u8)&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While constructing any specific LED, the logic is passed on as a &lt;em&gt;closure&lt;/em&gt;. By defining them as &lt;code&gt;const&lt;/code&gt;, I find it easier to read, test and if necessary, modify them:&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;fn&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;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;displayChar&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;hide_character&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nb"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;evaluator&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nb"&gt;u8&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;bool&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;Led&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;Led&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="nf"&gt;.to_string&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;
            &lt;span class="n"&gt;show_character&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;displayChar&lt;/span&gt;&lt;span class="nf"&gt;.to_string&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;
            &lt;span class="n"&gt;hide_character&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;hide_character&lt;/span&gt;&lt;span class="nf"&gt;.to_string&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;
            &lt;span class="n"&gt;light_status&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="k"&gt;false&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;on_receiving_next_signal&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;evaluator&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;Every LED has a &lt;code&gt;show_character&lt;/code&gt; and a &lt;code&gt;hide_character&lt;/code&gt; to represent its display in the &lt;em&gt;lit&lt;/em&gt; and &lt;em&gt;unlit&lt;/em&gt; mode. I have used special ASCII characters to help show a LED on the terminal. For example, for LED 'a', it is "━━━━" and for LED 'b', it is  " ┃": the space prefixed is for easier positioning on the screen. The section below exemplifies this.&lt;/p&gt;




&lt;p&gt;At the call-site of calling the constructor of LED 'a':&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Led::new("a", "━━━━", "    ", LED_A_GATE_LOGIC /* closure as a const */);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Data and Code structure
&lt;/h4&gt;

&lt;p&gt;This is the easier part. Using regular OO technique:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A &lt;em&gt;DisplayUnit&lt;/em&gt; is composed of 7 LEDs of its own and is responsible for constructing those&lt;/li&gt;
&lt;li&gt;A &lt;em&gt;ScreenClock&lt;/em&gt; is composed of 6 DisplayUnits and is responsible for constructing those&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A &lt;code&gt;DisplayUnit&lt;/code&gt; is a &lt;code&gt;struct&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;pub&lt;/span&gt; &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;DigitDisplayUnit&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// TODO: These leds should be in a map, identifiable  by the letter associated&lt;/span&gt;
    &lt;span class="n"&gt;led_a&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Led&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;led_b&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Led&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;led_c&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Led&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;led_d&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Led&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;led_e&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Led&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;led_f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Led&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;led_g&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Led&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;impl&lt;/span&gt; &lt;span class="n"&gt;DigitDisplayUnit&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;new&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;DigitDisplayUnit&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;leda&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Led&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="s"&gt;"a"&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="s"&gt;"    "&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;LED_A_GATE_LOGIC&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;ledb&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;Led&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="s"&gt;"b"&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="s"&gt;"  "&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;     &lt;span class="n"&gt;LED_B_GATE_LOGIC&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
       &lt;span class="c1"&gt;// ...&lt;/span&gt;

        &lt;span class="n"&gt;DigitDisplayUnit&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;led_a&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;leda&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;led_b&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;ledb&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="c1"&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;So, to create a ScreenClock, we do 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;pub&lt;/span&gt; &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;ScreenClock&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;top_left_row&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;u8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;top_left_col&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;u8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;display_units&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;DigitDisplayUnit&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;impl&lt;/span&gt; &lt;span class="n"&gt;ScreenClock&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;fn&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;start_at_row&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;u8&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;start_at_col&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;u8&lt;/span&gt; &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;ScreenClock&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

        &lt;span class="c1"&gt;// From left to right, on the display panel!&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;digital_display_unit0&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;DigitDisplayUnit&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="c1"&gt;// h_ of hh&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;digital_display_unit1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;DigitDisplayUnit&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="c1"&gt;// _h of hh&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;digital_display_unit2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;DigitDisplayUnit&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="c1"&gt;// m_ of mm&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;digital_display_unit3&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;DigitDisplayUnit&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="c1"&gt;// _m of mm&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;digital_display_unit4&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;DigitDisplayUnit&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="c1"&gt;// s_ of ss&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;digital_display_unit5&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nn"&gt;DigitDisplayUnit&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="c1"&gt;// _s of ss&lt;/span&gt;


        &lt;span class="n"&gt;ScreenClock&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;top_left_row&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;start_at_row&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;top_left_col&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;start_at_col&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;display_units&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
                &lt;span class="n"&gt;digital_display_unit0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;digital_display_unit1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;digital_display_unit2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;digital_display_unit3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;digital_display_unit4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;digital_display_unit5&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="p"&gt;}&lt;/span&gt;
&lt;span class="c1"&gt;// ... rest of it&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once the skeleton is in place, solution becomes apparent to one:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Decide the position of the clock on the screen (row / column)&lt;/li&gt;
&lt;li&gt;Create a &lt;code&gt;ScreenClock&lt;/code&gt; ( refer to the constructor &lt;code&gt;new&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;Every second on the system's own date/time
-- Pass the current hour/minute/second readings to &lt;code&gt;ScreenClock&lt;/code&gt;
-- Refresh the &lt;code&gt;ScreenClock&lt;/code&gt; (i.e. produce the LEDs on the screen)&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;On the left, this digital clock and on the right, Unix &lt;code&gt;date&lt;/code&gt; command's output, on my Ubuntu 22.10 laptop, with terminal type &lt;em&gt;xterm-256color&lt;/em&gt; :&lt;/p&gt;

&lt;p&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%2F6qnpem9ollx48kkn4k00.gif" 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%2F6qnpem9ollx48kkn4k00.gif" alt="Screen play"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h4&gt;
  
  
  Respond to a tick
&lt;/h4&gt;

&lt;p&gt;The simplest way to get the current system time every second is to use &lt;code&gt;Local::now()&lt;/code&gt; from the &lt;code&gt;chrono::&lt;/code&gt; crate, after a second's duration and &lt;code&gt;sleep&lt;/code&gt;ing in between. However, my intention has been to implement a behaviour of reaction: let a nudge arrive at a second's frequency indicating that a second has elapsed and then, the current time be read again. This way there is no enforced &lt;code&gt;sleep&lt;/code&gt;ing.&lt;/p&gt;

&lt;p&gt;It turns out that &lt;code&gt;crossbeam::&lt;/code&gt; crate has exactly the facility that I need, a function named &lt;code&gt;tick&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="nn"&gt;crossbeam_channel&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="n"&gt;channel&lt;/span&gt;
&lt;span class="k"&gt;pub&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="nf"&gt;tick&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;duration&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;Duration&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is how I set it up:&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;notification_on_next_second&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;tick&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nn"&gt;Duration&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;from_secs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Whenever a tick arrives, the application reads the current time and uses that to drive the digital boolean logic, which lights up the LEDs as needed.&lt;/p&gt;

&lt;h4&gt;
  
  
  Trap CTRL-C to restore the cursor
&lt;/h4&gt;

&lt;p&gt;At the beginning, the application hides the cursor by issuing a ANSI Escape sequence, thus:&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="nd"&gt;print!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\x1b&lt;/span&gt;&lt;span class="s"&gt;[?25l"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the user terminates the program by pressing CTRL-C, I need to restore the blinking cursor; a well-behaved &lt;code&gt;DigitalClock&lt;/code&gt; must do that. Some kind of &lt;em&gt;signal handler&lt;/em&gt; is required, so that just before it exits, the application issues the complementary ANSI escape sequence that restores the cursor. This time, the standard library provides the handler facility, aptly named: &lt;code&gt;ctrlc&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;fn&lt;/span&gt; &lt;span class="nf"&gt;notify_me_when_user_exits&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;Receiver&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nb"&gt;u8&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nn"&gt;ctrlc&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;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sender&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;receiver&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;  &lt;span class="nf"&gt;bounded&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nn"&gt;ctrlc&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;set_handler&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;move&lt;/span&gt; &lt;span class="p"&gt;||&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nd"&gt;print!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\x1b&lt;/span&gt;&lt;span class="s"&gt;[?25h"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;  &lt;span class="c1"&gt;// Restore the hidden cursor!&lt;/span&gt;
        &lt;span class="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;_&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sender&lt;/span&gt;&lt;span class="nf"&gt;.send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0xFF&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="nf"&gt;Ok&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;receiver&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 little closure, named &lt;code&gt;ctrlc::set_handler&lt;/code&gt;  does the job. It makes use of a facility that &lt;code&gt;crossbeam_channel::bounded(n)&lt;/code&gt; provides. Upon trapping the CTRL-C, the closure issues an appropriate ANSI Escape sequence, and &lt;em&gt;sends&lt;/em&gt; a 0xFF (an arbitrary value, not used) in the &lt;em&gt;channel&lt;/em&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  Handling two non-deterministic asynchronous inputs
&lt;/h4&gt;

&lt;p&gt;The main thread sets itself up for two inputs:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A periodic tick: when it arrives, current time is picked up and the &lt;code&gt;DigitalClock&lt;/code&gt; displays the digits &lt;/li&gt;
&lt;li&gt;An intimation by the user to exit: when it arrives, the handler gets into action, keeps the house as it were and leaves.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Thus, a structure is required to respond to either of these two inputs which can arrive in an unforeseen order; as if, the application is &lt;em&gt;passively waiting&lt;/em&gt; for either of two interrupts and then &lt;em&gt;reacting to&lt;/em&gt; the one that arrives first.&lt;/p&gt;

&lt;p&gt;While strolling through rust-cli (&lt;a href="https://rust-cli.github.io/book/in-depth/signals.html" rel="noopener noreferrer"&gt;handbook&lt;/a&gt;), I have come across a nifty arrangement of &lt;code&gt;select!&lt;/code&gt; macro. This macro sits perfectly at the &lt;em&gt;receiving end&lt;/em&gt; of a (bi-ended) channel and executes logic associated with the receipt of data through that channel. Structurally, it caters to multiple such receiving ends but responds to any one of them at a given point in time:, much like its homographic elder cousin named &lt;code&gt;select()&lt;/code&gt; Unix system call:&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="nd"&gt;select!&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nf"&gt;recv&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;notification_on_next_second&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&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="k"&gt;let&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;read_clock_now&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;      &lt;span class="c1"&gt;// Current HH:MM:SS as a string&lt;/span&gt;
                &lt;span class="nf"&gt;.chars&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;                         &lt;span class="c1"&gt;// An iterator of characters it contains&lt;/span&gt;
                &lt;span class="nf"&gt;.filter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt; &lt;span class="p"&gt;|&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;  &lt;span class="p"&gt;|&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="sc"&gt;':'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;       &lt;span class="c1"&gt;// Scrape the ':' character from the middle&lt;/span&gt;
                &lt;span class="nf"&gt;.map&lt;/span&gt;&lt;span class="p"&gt;(|&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="p"&gt;|&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nb"&gt;u8&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="sc"&gt;'0'&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nb"&gt;u8&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;// Get the numeric digit from ascii digit&lt;/span&gt;
                &lt;span class="nf"&gt;.collect&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

                &lt;span class="n"&gt;screen_clock&lt;/span&gt;
                &lt;span class="nf"&gt;.on_next_second&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                    &lt;span class="n"&gt;hr_and_min_and_sec&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="n"&gt;hr_and_min_and_sec&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
                    &lt;span class="n"&gt;hr_and_min_and_sec&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
                    &lt;span class="n"&gt;hr_and_min_and_sec&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
                    &lt;span class="n"&gt;hr_and_min_and_sec&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
                    &lt;span class="n"&gt;hr_and_min_and_sec&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
                &lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="nf"&gt;.refresh&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

                &lt;span class="nd"&gt;print!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\x1b&lt;/span&gt;&lt;span class="s"&gt;[7A"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;

            &lt;span class="nf"&gt;recv&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;notification_on_user_exiting&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&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="nd"&gt;println!&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Goodbye!"&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="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The complete code is &lt;a href="https://github.com/nsengupta/rust-exploration-digital-clock" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;There it is, a simple application that makes use of some Rust facilities, idioms and techniques that I have managed to learn so far. It is not optimized for memory and speed and certainly, the code can be improved at few places, I know. Yet, I would love to hear from Rustaceans if and where do they think,the design can be cleaner and Rust's features can be adopted better. Educate me.&lt;/p&gt;




&lt;p&gt;I am a software programmer with ~3 decades of experience, having learnt through many successes I have influenced or caused, and many failures and mistakes I have made. I &lt;a href="https://www.linkedin.com/in/nirmalyasengupta/" rel="noopener noreferrer"&gt;work&lt;/a&gt; as a platform technologist with a consortium of consultants: &lt;a href="https://www.linkedin.com/company/swanspeed-consulting/about/" rel="noopener noreferrer"&gt;Swanspeed Consulting&lt;/a&gt;. &lt;/p&gt;

</description>
      <category>rust</category>
    </item>
    <item>
      <title>Aspiring to be a sparring partner of CTOs</title>
      <dc:creator>Nirmalya Sengupta</dc:creator>
      <pubDate>Sun, 14 May 2017 08:46:40 +0000</pubDate>
      <link>https://forem.com/baatchitweet/a-ctos-potential-sparring-partner</link>
      <guid>https://forem.com/baatchitweet/a-ctos-potential-sparring-partner</guid>
      <description>

</description>
      <category>scalajava</category>
      <category>akka</category>
      <category>sqlgraph</category>
      <category>fsm</category>
    </item>
  </channel>
</rss>
