<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>REBELSCIENCE</title><link>https://rebelscience.club/</link><description>Bioinformatics, Programming and Open-Source Science</description><item><title>From Python to Rust: Part 3.</title><link>https://rebelscience.club/2020/06/from-python-to-rust-part-3/</link><guid isPermaLink="true">https://rebelscience.club/2020/06/from-python-to-rust-part-3/</guid><pubDate>Tue, 23 Jun 2020 16:12:03 GMT</pubDate><description>Python dictionary, Rust HashMap and a DNA Reverse Complement function.
</description><content:encoded><![CDATA[
<p class="wp-block-paragraph">In our last article, we looked at how we can use Strings in Rust to store Genome data (DNA sequences). We will be using Strings extensively in our future code, as they are very convenient when it comes to storing and manipulating DNA/RNA data. </p>



<p class="wp-block-paragraph">In this article, we are taking a look at one more, very important data structure that we are going to need for more advanced algorithms. After we compare both Dictionaries (Python) and Hash Maps (Rust), we will implement a DNA <a rel="noreferrer noopener" href="https://rebelscience.club/2020/03/bioinformatics-in-python-dna-toolkit-part-2-transcription-and-reverse-complement/" target="_blank">reverse_complement</a> function.</p>



<hr class="wp-block-separator has-text-color has-background has-black-background-color has-black-color is-style-wide"/>



<h3 class="wp-block-heading">Part 1: Dictionary and a Hash Map</h3>



<hr class="wp-block-separator has-text-color has-background has-black-background-color has-black-color is-style-wide"/>



<p class="wp-block-paragraph">Let&#8217;s create two new files called <code>data_structures</code> in each folder (Python/Rust), and add an empty functions:</p>



<figure class="wp-block-image alignwide size-full"><a href="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_171151-1.png"><img decoding="async" width="1887" height="1154" src="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_171151-1.png" alt="Rust Bioinformatics" class="wp-image-745" srcset="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_171151-1.png 1887w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_171151-1-471x288.png 471w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_171151-1-1177x720.png 1177w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_171151-1-768x470.png 768w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_171151-1-1536x939.png 1536w" sizes="(max-width: 1887px) 100vw, 1887px" /></a><figcaption class="wp-element-caption">Click to enlarge/download</figcaption></figure>



<p class="wp-block-paragraph">For Python, we create a function <strong>dicts()</strong> and for Rust, we have <strong>_hash_maps()</strong> as that is what those data structures are called.</p>



<p class="wp-block-paragraph">Let&#8217;s start by taking a quick look at Python Dictionary, so we have a reference point for our Rust Hash Map version.</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Python&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">def dicts():
    test_dict = {}
    test_dict['Key_1'] = 'Value_1'
    test_dict['Key_2'] = 'Value_2'
    test_dict['Key_3'] = ['Value_1', 'Value_2']

    print(test_dict['Key_1'])

    if test_dict['Key_3']:
        print(test_dict['Key_3'])
        print(test_dict['Key_3'][1])

    for key, value in test_dict.items():
        print(key, value)</pre></div>


<p class="wp-block-paragraph">This is very easy, right? On the line 2 we create an empty dictionary and on lines 3-5 we add Key-Value pairs. Line 5 adds a List as a Value.</p>



<p class="wp-block-paragraph">On the line 7 we print the Value that &#8216;Key_1&#8217; is pointing at, which is a string &#8216;Value_1&#8217;.</p>



<p class="wp-block-paragraph">On the line 9, we make sure that our &#8216;test_dict&#8217; has a key &#8216;Key_3&#8217;, and if yes, we print its Value. In this case, Line 10 will print a List and the line 11 will print the second value of the list &#8216;Value_2&#8217;.</p>



<p class="wp-block-paragraph">And the last part is a For loop which accesses ‘items’ of our dictionary, which are Key-Value pairs, iterates through them and prints out both.</p>



<p class="wp-block-paragraph">If we now call this function in our main.py file, we should see this output:</p>



<figure class="wp-block-image alignwide size-full"><a href="https://rebelscience.club/wp-content/uploads/2020/06/image-17.png"><img decoding="async" width="1551" height="1077" src="https://rebelscience.club/wp-content/uploads/2020/06/image-17.png" alt="Rust Bioinformatics" class="wp-image-744" srcset="https://rebelscience.club/wp-content/uploads/2020/06/image-17.png 1551w, https://rebelscience.club/wp-content/uploads/2020/06/image-17-415x288.png 415w, https://rebelscience.club/wp-content/uploads/2020/06/image-17-1037x720.png 1037w, https://rebelscience.club/wp-content/uploads/2020/06/image-17-768x533.png 768w, https://rebelscience.club/wp-content/uploads/2020/06/image-17-1536x1067.png 1536w" sizes="(max-width: 1551px) 100vw, 1551px" /></a><figcaption class="wp-element-caption">Click to enlarge/download</figcaption></figure>



<p class="wp-block-paragraph">Now let&#8217;s see how we can replicate this in Rust:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">use std::collections::HashMap;

fn _hash_maps() {
    let mut test_hm = HashMap::new();
    test_hm.insert(&quot;Key_1&quot;, vec![&quot;Value_1&quot;]);
    test_hm.insert(&quot;Key_2&quot;, vec![&quot;Value_2&quot;]);
    test_hm.insert(&quot;Key_3&quot;, vec![&quot;Value_1&quot;, &quot;Value_2&quot;]);

    // println!(&quot;{}&quot;, test_hm[&quot;Key_1&quot;]);
    println!(&quot;{:?}&quot;, test_hm[&quot;Key_1&quot;]);

    if test_hm.contains_key(&quot;Key_3&quot;) {
        println!(&quot;{:?}&quot;, test_hm[&quot;Key_3&quot;]);
        println!(&quot;{:?}&quot;, test_hm[&quot;Key_3&quot;][1]);
    }

    for (key, value) in &amp;test_hm {
        println!(&quot;{} {:?}&quot;, key, value);
    }
}</pre></div>


<p class="wp-block-paragraph">On the line 1 we are including a HashMap module as it is not included in Rust by default, unlike Vectors.</p>



<p class="wp-block-paragraph">On the line 4 we create an empty Hash Map (a dictionary in Python).</p>



<p class="wp-block-paragraph">On lines 5–7 we insert 3 Key-Value pairs the same way as in Python, but in Rust we need to call ‘insert’ method on our Hash Map. If we want to add a Vector with multiple values, like we do on the line 7, we need to make a Vector the default Value type for the whole Hash Map. This is even if we add a single Value like we do on lines 5 and 6.</p>



<p class="wp-block-paragraph">Line 9 is there but is commented out. You can see that we are trying to print the Value that has a Key “Key_1”, using ‘{}’. This will generate the following error:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;full&quot;,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">error[E0277]: `std::vec::Vec&lt;&amp;str&gt;` doesn't implement `std::fmt::Display`
  --&gt; src/dna_toolkit.rs:24:20
   |
24 |     println!(&quot;{}&quot;, test_hm[&quot;Key_1&quot;]);
   |                    ^^^^^^^^^^^^^^^^ `std::vec::Vec&lt;&amp;str&gt;` cannot be formatted with the default formatter
   |
   = help: the trait `std::fmt::Display` is not implemented for `std::vec::Vec&lt;&amp;str&gt;`
   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
   = note: required by `std::fmt::Display::fmt`
   = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)</pre></div>


<p class="wp-block-paragraph">Amazing that the Rust compiler not only tells us that something is wrong, but also suggests a fix. Let&#8217;s use {:?} to format our output, which is a Vector in this case. </p>



<p class="wp-block-paragraph">The rest of the code is almost identical to Python. The only difference is in Rust, we use &#8216;<strong>contains_key</strong>&#8216; method to check if a Key is in our Hash Map. Last For loop has the same structure, and does not even require <strong>items() </strong>method like Python does. Here is the final version:</p>



<figure class="wp-block-image alignwide size-full"><a href="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_175404.png"><img decoding="async" width="1702" height="1154" src="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_175404.png" alt="Rust Bioinformatics" class="wp-image-748" srcset="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_175404.png 1702w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_175404-425x288.png 425w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_175404-1062x720.png 1062w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_175404-768x521.png 768w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_175404-1536x1041.png 1536w" sizes="(max-width: 1702px) 100vw, 1702px" /></a><figcaption class="wp-element-caption">Click to enlarge/download</figcaption></figure>



<hr class="wp-block-separator has-text-color has-background has-black-background-color has-black-color is-style-wide"/>



<h3 class="wp-block-heading">Part 2: DNA Reverse Complement function</h3>



<hr class="wp-block-separator has-text-color has-background has-black-background-color has-black-color is-style-wide"/>



<p class="wp-block-paragraph">Now that we are armed with Dictionaries/Hash Maps, let&#8217;s take our existing <a rel="noreferrer noopener" href="https://rebelscience.club/2020/03/bioinformatics-in-python-dna-toolkit-part-2-transcription-and-reverse-complement/" target="_blank">DNA Reverse Complement</a> function and port it to Rust. In this function we want to map one type of character to another, and given a string, use that map as a translator to generate a new string. We also want to reverse the result before we return it. Let’s go back to dna_toolkit.py/.rs files and add a new function.</p>



<p class="wp-block-paragraph">So here is our Python version:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Python&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">def reverse_complement(dna):
   	&quot;&quot;&quot;
    Generating a complement string and returning
    reveresed version.
    &quot;&quot;&quot;
    trans_dict = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
    complement_dna = &quot;&quot;

    for nuc in dna:
        complement_dna += trans_dict[nuc]

    return complement_dna[::-1]</pre></div>


<p class="wp-block-paragraph">Nice, clean, and easy, right? This function accepts a string and returns a string.</p>



<p class="wp-block-paragraph">We just predefine a &#8216;trans_dict&#8217;, translation dictionary on the line 6, which we use as a mapper. On line 7 we create an empty string we will use to accumulate a new set of values in.</p>



<p class="wp-block-paragraph">For loop on line 9 just loops through each character in the string of <strong>dna</strong> we passed to that function and checks them against the dictionary, and appends a mapped character to the &#8216;complement_dna&#8217; string.</p>



<p class="wp-block-paragraph">Last line 12 returns a reversed version of &#8216;complement_dna&#8217;.</p>



<p class="wp-block-paragraph">So if we run our code now, we should see this:</p>



<figure class="wp-block-image alignwide size-full"><a href="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_181119.png"><img decoding="async" width="1693" height="1067" src="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_181119.png" alt="Rust Bioinformatics" class="wp-image-749" srcset="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_181119.png 1693w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_181119-457x288.png 457w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_181119-1142x720.png 1142w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_181119-768x484.png 768w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_181119-1536x968.png 1536w" sizes="(max-width: 1693px) 100vw, 1693px" /></a><figcaption class="wp-element-caption">Click to enlarge/download</figcaption></figure>



<p class="wp-block-paragraph">We pass &#8220;ATCG&#8221; into our new function, it is being mapped against our mapping dictionary and &#8220;TAGC&#8221; is being generated. A reversed version is returned, and we see &#8216;CGAT&#8217; in our output window.</p>



<p class="wp-block-paragraph">Here is &#8216;Pythonic&#8217; version of the same code. Let&#8217;s hope Rust will gain that type of functionality in the future. You could start your own Rust &#8216;crate&#8217; and replicate this type of functionality and share it with the community.</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Python&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">def reverse_complement(self):
   	&quot;&quot;&quot;
    Generating a complement string and returning
    reveresed version.
    &quot;&quot;&quot;
    mapping = str.maketrans('ATCG', 'TAGC')
    return self.seq.translate(mapping)[::-1]</pre></div>


<p class="wp-block-paragraph">Here is the Rust version:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;wide&quot;,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">fn _reverse_complement(dna: &amp;String) -&gt; String {
    // Generating a complement string and returning
    // reveresed version.
    let trans_hashmap: HashMap&lt;char, char&gt; = [('A', 'T'), ('T', 'A'), ('C', 'G'), ('G', 'C')]
        .iter()
        .copied()
        .collect();

    let mut complement_dna = String::new();

    for nuc in dna.chars().rev() {
        complement_dna.push(trans_hashmap[&amp;nuc]);
    }

    return complement_dna;
}</pre></div>


<p class="wp-block-paragraph">Same as Python, it accepts a string and returns a string. On line 4 we attempt to replicate Python as much as we can. The part after <strong>= </strong>is an array, so we need to convert it into a collection, copy that collection into a Hash Map and return an iterator. That is why we have those 3 methods after our Hash Map. I suggest you read about these methods here: <a rel="noreferrer noopener" href="https://doc.rust-lang.org/std/iter/" target="_blank">.iter()</a>, <a rel="noreferrer noopener" href="https://doc.rust-lang.org/std/iter/struct.Copied.html" target="_blank">.copied()</a> and here <a rel="noreferrer noopener" href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect" target="_blank">.collect()</a>.</p>



<p class="wp-block-paragraph">Line 9 is a new empty string (from our previous <a rel="noreferrer noopener" href="https://rebelscience.club/2020/06/from-python-to-rust-part-2-strings-functions-crates-modules/" target="_blank">article</a>).</p>



<p class="wp-block-paragraph">Lines 11, 12 and 15 are almost the same as Python. The only difference being that in Rust, we use &#8216;<strong>dna.chars().rev()</strong>&#8216; to loop through the reversed set of characters from &#8216;<strong>dna</strong>&#8216; and return a string, while In Python we loop through the normal string, and then we reverse it before returning it. Subtle but important difference.</p>



<p class="wp-block-paragraph">Note, that our mapper &#8216;trans_hashmap&#8217; is immutable. We can make it mutable and use <strong>.insert()</strong> method like this:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">let mut trans_dict = HashMap::new();
trans_dict.insert('A', 'T');
trans_dict.insert('T', 'A');
trans_dict.insert('C', 'G');
trans_dict.insert('G', 'C');</pre></div>


<p class="wp-block-paragraph">But a static, immutable version should be a faster solution. In this case, we have a fixed set of characters that will not change. So the original approach makes more sense.</p>



<p class="wp-block-paragraph">Here is the final result:</p>



<figure class="wp-block-image alignwide size-full"><a href="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_185218.png"><img decoding="async" width="1698" height="1074" src="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_185218.png" alt="Rust Bioinformatics" class="wp-image-752" srcset="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_185218.png 1698w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_185218-455x288.png 455w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_185218-1138x720.png 1138w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_185218-768x486.png 768w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_185218-1536x972.png 1536w" sizes="(max-width: 1698px) 100vw, 1698px" /></a><figcaption class="wp-element-caption">Click to enlarge/download</figcaption></figure>



<p class="wp-block-paragraph">We need to tweak the value we pass to be printed in Rust. If we try to pass just &#8220;ATCG&#8221;, Rust will tell us that we are passing a slice &#8216;str&#8217; but our function is expecting a reference to a string &#8216;&amp;String&#8217;. So we need to convert &#8216;str&#8217; to a String and pass it by reference.</p>



<p class="wp-block-paragraph">Now let&#8217;s finish by using our random DNA generator and look at the final result for both languages:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><a href="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_190026_2.png"><img decoding="async" width="976" height="1119" src="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_190026_2.png" alt="Rust Bioinformatics" class="wp-image-753" srcset="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_190026_2.png 976w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_190026_2-251x288.png 251w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_190026_2-628x720.png 628w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_190026_2-768x881.png 768w" sizes="(max-width: 976px) 100vw, 976px" /></a><figcaption>Rust</figcaption></figure></div>



<div class="wp-block-image"><figure class="aligncenter size-full"><a href="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_190026-1.png"><img decoding="async" width="977" height="1121" src="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_190026-1.png" alt="Rust Bioinformatics" class="wp-image-755" srcset="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_190026-1.png 977w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_190026-1-251x288.png 251w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_190026-1-628x720.png 628w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200623_190026-1-768x881.png 768w" sizes="(max-width: 977px) 100vw, 977px" /></a><figcaption>Python</figcaption></figure></div>



<p class="wp-block-paragraph">Alright. This is it for this article. See you in the next one.</p>



<hr class="wp-block-separator has-text-color has-background has-black-background-color has-black-color is-style-wide"/>



<h3 class="wp-block-heading">Links</h3>



<hr class="wp-block-separator has-text-color has-background has-black-background-color has-black-color is-style-wide"/>



<ul class="wp-block-list"><li>Rust HashMap video #1:&nbsp;<a rel="noreferrer noopener" href="https://youtu.be/sTK8fagTsMk" target="_blank">https://youtu.be/sTK8fagTsMk</a></li><li>Rust HashMap video #2:&nbsp;<a rel="noreferrer noopener" href="https://www.tutorialspoint.com/rust/rust_string.htm" target="_blank">https://youtu.be/ic9WEuto-gE</a></li></ul>



<p class="wp-block-paragraph"><strong>GitHub:&nbsp;<a href="https://github.com/rebelC0der/From_Python_To_Rust">https://github.com/rebelC0der/From_Python_To_Rust</a></strong></p>



<p class="wp-block-paragraph"><strong>Recommended Rust programming book:</strong></p>



<div class="wp-block-image"><figure class="aligncenter is-resized"><img decoding="async" src="https://images-na.ssl-images-amazon.com/images/I/71qj8wdDtjL.jpg" alt="Mastering Rust: Learn about memory safety, type system, concurrency, and the new features of Rust 2018 edition, 2nd Edition" width="353" height="436"/><figcaption>Mastering Rust: Learn about memory safety, type system, concurrency, and the new features of Rust 2018 edition, 2nd Edition<br>(<a href="https://amzn.to/2TLd7Yt" target="_blank" rel="noreferrer noopener">UK</a> / <a href="https://amzn.to/2zCSSFI" target="_blank" rel="noreferrer noopener">US</a>)</figcaption></figure></div>



<p class="wp-block-paragraph"><strong>For a video versions of these articles, check out my playlist here:</strong></p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="From Python to Rust. Part 3: A Dictionary and a HashMap." width="640" height="360" src="https://www.youtube.com/embed/DpUtAFCQVRE?list=PLpSOMAcxEB_i81xOdcgL8-Lp8lbrTxEI3" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p class="wp-block-paragraph"></p>
]]></content:encoded></item><item><title>From Python to Rust: Part 2.</title><link>https://rebelscience.club/2020/06/from-python-to-rust-part-2-strings-functions-crates-modules/</link><guid isPermaLink="true">https://rebelscience.club/2020/06/from-python-to-rust-part-2-strings-functions-crates-modules/</guid><pubDate>Thu, 04 Jun 2020 12:07:08 GMT</pubDate><description>Strings, Functions, Random number generation and Rust crates/modules.
</description><content:encoded><![CDATA[
<p class="wp-block-paragraph">In our &#8220;dna_toolkit&#8221; series, we used Python Strings, Lists, and Dictionaries extensively. These data structures are very useful and make our life very easy. Let&#8217;s see what Rust has to offer. </p>



<p class="wp-block-paragraph">We start with <code>Strings</code>. Rust has two types. One, called &#8216;String slice&#8217;, and the other one is more like a string in other languages, which is just &#8216;String&#8217;. I am going to link to an amazing video about Strings in Rust in the &#8216;Links&#8217; section below. Please make sure to watch it if you are completely new to this part of Rust.</p>



<p class="wp-block-paragraph">In this article, we will focus on looking at how we can use Strings in Rust to replicate some of our &#8216;dna_toolkit&#8217; code. In a previous article, we created two files for Rust and Python: &#8216;<strong>main.rs</strong>&#8216; and &#8216;<strong>main.py</strong>&#8216; respectively. We added all the code into those two files.</p>



<p class="wp-block-paragraph">To avoid adding a lot of code into one file, let&#8217;s create separate files for each video, wrap the code into functions and include/import them into our &#8216;<strong>main</strong>&#8216; files.</p>



<p class="wp-block-paragraph">So here is the project structure we created in our first article:</p>



<figure class="wp-block-image alignwide size-full"><a href="https://rebelscience.club/wp-content/uploads/2020/06/image-7.png"><img decoding="async" width="1760" height="1123" src="https://rebelscience.club/wp-content/uploads/2020/06/image-7.png" alt="Rust Bioinformatics" class="wp-image-668" srcset="https://rebelscience.club/wp-content/uploads/2020/06/image-7.png 1760w, https://rebelscience.club/wp-content/uploads/2020/06/image-7-451x288.png 451w, https://rebelscience.club/wp-content/uploads/2020/06/image-7-1128x720.png 1128w, https://rebelscience.club/wp-content/uploads/2020/06/image-7-768x490.png 768w, https://rebelscience.club/wp-content/uploads/2020/06/image-7-1536x980.png 1536w" sizes="(max-width: 1760px) 100vw, 1760px" /></a><figcaption class="wp-element-caption">Click to enlarge/download</figcaption></figure>



<p class="wp-block-paragraph">Let&#8217;s create two new files; &#8216;<strong>intro.py</strong>&#8216; and &#8216;<strong>intro.rs</strong>&#8216;, move all the code from our &#8216;<strong>main</strong>&#8216; files into those files, and include/import them. So now our project should look like this:</p>



<figure class="wp-block-image alignwide size-full"><a href="https://rebelscience.club/wp-content/uploads/2020/06/image-9.png"><img decoding="async" width="1735" height="1337" src="https://rebelscience.club/wp-content/uploads/2020/06/image-9.png" alt="Rust Bioinformatics" class="wp-image-674" srcset="https://rebelscience.club/wp-content/uploads/2020/06/image-9.png 1735w, https://rebelscience.club/wp-content/uploads/2020/06/image-9-374x288.png 374w, https://rebelscience.club/wp-content/uploads/2020/06/image-9-934x720.png 934w, https://rebelscience.club/wp-content/uploads/2020/06/image-9-768x592.png 768w, https://rebelscience.club/wp-content/uploads/2020/06/image-9-1536x1184.png 1536w" sizes="(max-width: 1735px) 100vw, 1735px" /></a><figcaption class="wp-element-caption">Click to enlarge/download</figcaption></figure>



<p class="wp-block-paragraph">Now that we have established the structure we will use, let&#8217;s add two more files called &#8216;<strong>strings</strong>&#8216; and proceed to our first segment.</p>



<hr class="wp-block-separator has-text-color has-black-color has-css-opacity has-black-background-color has-background is-style-wide"/>



<h3 class="wp-block-heading">Part 1: Strings</h3>



<hr class="wp-block-separator has-text-color has-black-color has-css-opacity has-black-background-color has-background is-style-wide"/>



<p class="wp-block-paragraph">So now we should have something like this:</p>



<figure class="wp-block-image alignwide size-full"><a href="https://rebelscience.club/wp-content/uploads/2020/06/image-10.png"><img decoding="async" width="1501" height="576" src="https://rebelscience.club/wp-content/uploads/2020/06/image-10.png" alt="Rust Bioinformatics" class="wp-image-676" srcset="https://rebelscience.club/wp-content/uploads/2020/06/image-10.png 1501w, https://rebelscience.club/wp-content/uploads/2020/06/image-10-512x196.png 512w, https://rebelscience.club/wp-content/uploads/2020/06/image-10-1280x491.png 1280w, https://rebelscience.club/wp-content/uploads/2020/06/image-10-768x295.png 768w" sizes="(max-width: 1501px) 100vw, 1501px" /></a><figcaption class="wp-element-caption">Click to enlarge/download</figcaption></figure>



<p class="wp-block-paragraph">Note, that we added the underscore symbol to our Rust functions: <strong>_intro()</strong>, <strong>_strings()</strong>. This is to avoid this compiler warning message:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">&lt;strong&gt;= note: `#[warn(dead_code)]` on by default&lt;/strong&gt;</pre></div>


<p class="wp-block-paragraph">We will comment out calls to previous functions to avoid a lot of output at the same time, so we can focus only on the output of the current article code. In this case, Rust tells us that there is a &#8216;dead code&#8217;, meaning we have a function <strong>_intro()</strong> that is included but never called. This is not a problem, just remember to add underscore to all Rust functions that you are not using/calling.</p>



<p class="wp-block-paragraph">We will focus on a<strong> String</strong> as it is a heap allocated data structure, meaning we can change it during the runtime, and it has a set of very useful methods.</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Python&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">test_str = &quot;Doom&quot;
print(test_str)

test_str += &quot; III&quot;
print(test_str)

test_str += '!'
print(test_str)</pre></div>

<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">let mut test_str = String::from(&quot;Doom&quot;);
println!(&quot;{}&quot;, test_str);

test_str.push_str(&quot; III&quot;);
println!(&quot;{}&quot;, test_str);

test_str.push('!');
println!(&quot;{}&quot;, test_str);</pre></div>


<p class="wp-block-paragraph">Python doesn&#8217;t care if you add a <strong>&#8216;character&#8217;</strong> or another <strong>&#8220;String&#8221;</strong> to our main string, but Rust is strict about it. Here we have two Rust methods for:</p>



<ul class="wp-block-list">
<li><strong>push_str(&#8221; &#8220;);</strong> &#8211; adds a string. Requires double quotes <strong>&#8221; &#8220;</strong>. Line 4.</li>



<li><strong>push(&#8216; &#8216;);</strong>  &#8211; adds a single character. Requires single quotes <strong>&#8216; &#8216;</strong>. Line 7.</li>
</ul>



<p class="wp-block-paragraph">If in Python we just say<code>test_str = "Doom"</code> and Python can understand it is a string, in Rust we need to tell the compiler explicitly: <code>let mut test_str = String::from("Doom");</code></p>



<p class="wp-block-paragraph">You can also create an empty <strong>String</strong> like this:<br><code>let mut test_str = String::new();</code></p>



<p class="wp-block-paragraph">Both codes will output this:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;shell&quot;,&quot;mime&quot;:&quot;text/x-sh&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Shell&quot;,&quot;language&quot;:&quot;Shell&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;shell&quot;}">Doom
Doom III
Doom III!</pre></div>


<p class="wp-block-paragraph">Check out a few other methods Rust <strong>String</strong> has : <a href="https://www.tutorialspoint.com/rust/rust_string.htm" target="_blank" rel="noreferrer noopener">https://www.tutorialspoint.com/rust/rust_string.htm</a></p>



<p class="wp-block-paragraph">Let&#8217;s combine two existing strings:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Python&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">p1 = &quot;Duke&quot;
p2 = &quot; Nukem&quot;

p3 = p1 + p2
print(f&quot;{p1} {p2} {p3}&quot;)</pre></div>


<p class="wp-block-paragraph">This is easy in Python. It just works, and we can keep accessing all three variables after we run this code.</p>



<p class="wp-block-paragraph">If we attempt to do the same in Rust, we will run into an issue. Let&#8217;s take a look:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">let p1 = String::from(&quot;Duke&quot;);
let p2 = String::from(&quot; Nukem&quot;);

let p3 = p1 + &amp;p2;
println!(&quot;{} {} {}&quot;, p1, p2, p3) // Will generate an error</pre></div>


<p class="wp-block-paragraph">Note, that when we add strings, the first string does not have ampersand <strong>&amp;</strong> symbol. Every string we add after that has to have <strong>&amp;</strong> symbol.</p>



<p class="wp-block-paragraph">If we run this, we will see this issue:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">&lt;strong&gt;println!(&quot;{} {} {}&quot;, p1, p2, p3);
                   | ^^ value borrowed here after move&lt;/strong&gt;</pre></div>


<p class="wp-block-paragraph">On the line 4 we gave the ownership of <strong>p1</strong> to <strong>p3</strong>, and we attempt to access it again on the line 5, by printing it out. <strong>p1</strong> does not exist at this point, as the ownership has been transferred to <strong>p3</strong>.</p>



<p class="wp-block-paragraph">We need to use Rust&#8217;s &#8216;<strong>format!</strong>&#8216; function, which will &#8216;borrow&#8217; <strong>p1</strong>, and <strong>p2</strong> memory locations to construct <strong>p3</strong> and will not affect ownership of any variable:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">let p1 = String::from(&quot;Duke&quot;);
let p2 = String::from(&quot; Nukem&quot;);

let p3 = String::from(format!(&quot;{} {}&quot;, p1, p2));
println!(&quot;{} {} {}&quot;, p1, p2, p3);</pre></div>


<p class="wp-block-paragraph">Now we have replicated Python&#8217;s behavior. Both should output this:</p>



<p class="wp-block-paragraph"><code>Duke Nukem Duke Nuke</code></p>



<p class="wp-block-paragraph">Now, let&#8217;s take a quick look at how we can print out individual characters, indices, and part of the string (a slice):</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Python&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Print each character:
for ch in p3:
    print(ch)

# Print each character and it's index:
for pos, ch in enumerate(p3):
    print(pos, ch)

# Print a slice of the string
print(p3[0:5])</pre></div>

<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">for ch in p3.chars() {
    println!(&quot;{}&quot;, ch);
}

for (ind, ch) in p3.char_indices() {
    println!(&quot;{} - {}&quot;, ind, ch);
}

println!(&quot;{}&quot;, &amp;p3[0..5]);</pre></div>


<p class="wp-block-paragraph">The code looks very similar as you can see. In Rust, we use the <code>chars()</code> method to get a single character and <code>char_indices()</code> to get an index and a character. Slicing is almost identical.</p>



<hr class="wp-block-separator has-text-color has-black-color has-css-opacity has-black-background-color has-background is-style-wide"/>



<h3 class="wp-block-heading">Part 2: Rand module (crate)</h3>



<hr class="wp-block-separator has-text-color has-black-color has-css-opacity has-black-background-color has-background is-style-wide"/>



<p class="wp-block-paragraph">Now that we are armed with basic Rust <strong>String</strong> knowledge, let&#8217;s quickly port two &#8220;<em>DNA Toolkit</em>&#8221; functions. For that, we will need to use a random number generator. Random module is a part of Python and can just be included  and used, but in Rust we need to add it as a dependence, build it, and only then we can use it. But this is super easy, as you will see.</p>



<p class="wp-block-paragraph">Project dependencies configuration can be found in <code>Cargo.toml</code> file:</p>



<figure class="wp-block-image size-full"><a href="https://rebelscience.club/wp-content/uploads/2020/06/image-11.png"><img decoding="async" width="710" height="567" src="https://rebelscience.club/wp-content/uploads/2020/06/image-11.png" alt="Rust Bioinformatics" class="wp-image-680" srcset="https://rebelscience.club/wp-content/uploads/2020/06/image-11.png 710w, https://rebelscience.club/wp-content/uploads/2020/06/image-11-361x288.png 361w" sizes="(max-width: 710px) 100vw, 710px" /></a><figcaption class="wp-element-caption">Click to enlarge/download</figcaption></figure>



<p class="wp-block-paragraph">Before we just blindly add a module, let&#8217;s see how we can search for it. Open your terminal, make sure it is in &#8216;dna_engine&#8217; folder, or use the built-in terminal and execute <code>cargo search</code> to search for <code>rand</code> module (crate).</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;shell&quot;,&quot;mime&quot;:&quot;text/x-sh&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Shell&quot;,&quot;language&quot;:&quot;Shell&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;shell&quot;}">cargo search rand</pre></div>


<p class="wp-block-paragraph">We can see we found the module we need:</p>



<figure class="wp-block-image alignwide size-full"><a href="https://rebelscience.club/wp-content/uploads/2020/06/image-12.png"><img decoding="async" width="1528" height="991" src="https://rebelscience.club/wp-content/uploads/2020/06/image-12.png" alt="Rust Bioinformatics" class="wp-image-681" srcset="https://rebelscience.club/wp-content/uploads/2020/06/image-12.png 1528w, https://rebelscience.club/wp-content/uploads/2020/06/image-12-444x288.png 444w, https://rebelscience.club/wp-content/uploads/2020/06/image-12-1110x720.png 1110w, https://rebelscience.club/wp-content/uploads/2020/06/image-12-768x498.png 768w" sizes="(max-width: 1528px) 100vw, 1528px" /></a><figcaption class="wp-element-caption">Click to enlarge/download</figcaption></figure>



<p class="wp-block-paragraph">Now let&#8217;s add it to our project. Modify <code>Cargo.toml</code> file Line 7-8 to look like this:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;toml&quot;,&quot;mime&quot;:&quot;text/x-toml&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;TOML&quot;,&quot;language&quot;:&quot;TOML&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;toml&quot;}">[dependencies]
rand = &quot;0.7&quot;</pre></div>


<p class="wp-block-paragraph">That&#8217;s it. When we finish writing a function (next segment) that will need this module, and run that function, Rust will see that we are trying to use this module. It will see we have added it to <code>[dependencies]</code> and download/build it for us.</p>



<hr class="wp-block-separator has-text-color has-black-color has-css-opacity has-black-background-color has-background is-style-wide"/>



<h3 class="wp-block-heading">Part 3: Random DNA sequence generation</h3>



<hr class="wp-block-separator has-text-color has-black-color has-css-opacity has-black-background-color has-background is-style-wide"/>



<p class="wp-block-paragraph">Let&#8217;s add two new files: <code>dna_toolkit.py</code> and <code>dna_toolkit.rs</code>. This is where our two new function will live.</p>



<p class="wp-block-paragraph">So here is our random DNA sequence generation function: (we use a loop in Python instead of list comprehension for demonstration purpose)</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Python&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">from random import choice

def gen_random_seq(length):
    nucleuotides = ['A', 'C', 'G', 'T']
    rnd_str = &quot;&quot;

    for _ in range(length):
        rnd_str += choice(nucleuotides)

    return rnd_str</pre></div>

<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;wide&quot;,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">use rand::Rng;

fn _gen_random_seq(length: i32) -&gt; String {
    let nucleuotides = vec!['A', 'C', 'G', 'T'];
    let mut rnd_str = String::new();

    for _ in 0..length {
        rnd_str.push(nucleuotides[rand::thread_rng().gen_range(0, nucleuotides.len())]);
    }
    return rnd_str;
}</pre></div>


<p class="wp-block-paragraph">The structure is very similar.</p>



<ul class="wp-block-list">
<li>Line 1: We import/include random modules. choice/rand.</li>



<li>Line 3: While in Python we don&#8217;t have to specify the type of the parameter and a return type, in Rust we need to do that. <code>length: i32</code> tells the compiler we will be passing an integer to our function, and <code>-&gt; String</code> part tells the compiler we will be returning a <strong>String</strong>.</li>



<li>Line 8: Python code definitely looks cleaner, but Rust is not much harder to read. We are just asking the <code>rand</code> module to generate a random number in range from <code>0</code> to the <code>length</code> of the vector that has 4 nucleotide character in it. We <code>push</code> that randomly picked character onto our string. The only extra bit we have here is <code>thread_rng()</code>. As per Rust documentation: &#8220;<em>Retrieve the lazily-initialized thread-local random number generator, seeded by the system</em>&#8220;</li>
</ul>



<hr class="wp-block-separator has-text-color has-black-color has-css-opacity has-black-background-color has-background is-style-wide"/>



<h3 class="wp-block-heading">Part 4: DNA to RNA transcription </h3>



<hr class="wp-block-separator has-text-color has-black-color has-css-opacity has-black-background-color has-background is-style-wide"/>



<p class="wp-block-paragraph">In transcription, we just need to replace all &#8216;T&#8217; &#8211; thymine nucleotides with &#8216;U&#8217; &#8211; uracil. This is done with just one line of code in each, as Python and Rust have built-in functions for that:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Python&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">def transcription(dna):
    return dna.replace(&quot;T&quot;, &quot;U&quot;)</pre></div>

<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">fn _transcription(dna: &amp;String) -&gt; String {
    return dna.replace(&quot;T&quot;, &quot;U&quot;);
}</pre></div>


<p class="wp-block-paragraph">Easy, right? Now let&#8217;s look at both files side by side:</p>



<figure class="wp-block-image alignwide size-full"><a href="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200604_144645.png"><img decoding="async" width="1843" height="1064" src="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200604_144645.png" alt="Rust Bioinformatics" class="wp-image-683" srcset="https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200604_144645.png 1843w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200604_144645-499x288.png 499w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200604_144645-1247x720.png 1247w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200604_144645-768x443.png 768w, https://rebelscience.club/wp-content/uploads/2020/06/Screenshot_20200604_144645-1536x887.png 1536w" sizes="(max-width: 1843px) 100vw, 1843px" /></a><figcaption class="wp-element-caption">Click to enlarge/download</figcaption></figure>



<p class="wp-block-paragraph">And let&#8217;s try adding the output to our <code>main</code> files to test our new functions:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Python&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">from intro import intro
from strings import strings
from dna_toolkit import gen_random_seq, transcription

if __name__ == &quot;__main__&quot;:
    print(&quot;Hello, I am Python!&quot;)

    # intro()
    # strings()

    dna = gen_random_seq(20)
    print(dna)
    print(transcription(dna))</pre></div>

<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">include!(&quot;intro.rs&quot;);
include!(&quot;strings.rs&quot;);
include!(&quot;dna_toolkit.rs&quot;);

fn main() {
    println!(&quot;Hello, I am Rust and I am fast&quot;);
  
  	// intro();
    // _strings();
    
  	let dna = String::from(_gen_random_seq(20));
    println!(&quot;{}&quot;, &amp;dna);
    println!(&quot;{}&quot;, _transcription(&amp;dna));
}</pre></div>


<p class="wp-block-paragraph">And here are the outputs from both:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://rebelscience.club/wp-content/uploads/2020/06/image-13.png"><img decoding="async" width="298" height="103" src="https://rebelscience.club/wp-content/uploads/2020/06/image-13.png" alt="Rust Bioinformatics" class="wp-image-684"/></a><figcaption class="wp-element-caption">Click to enlarge/download</figcaption></figure>
</div>

<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://rebelscience.club/wp-content/uploads/2020/06/image-15.png"><img decoding="async" width="449" height="106" src="https://rebelscience.club/wp-content/uploads/2020/06/image-15.png" alt="Rust Bioinformatics" class="wp-image-686"/></a><figcaption class="wp-element-caption">Click to enlarge/download</figcaption></figure>
</div>


<p class="wp-block-paragraph">And here is how our file structure should look like so far:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://rebelscience.club/wp-content/uploads/2020/06/image-16.png"><img decoding="async" width="536" height="798" src="https://rebelscience.club/wp-content/uploads/2020/06/image-16.png" alt="Rust Bioinformatics" class="wp-image-690" srcset="https://rebelscience.club/wp-content/uploads/2020/06/image-16.png 536w, https://rebelscience.club/wp-content/uploads/2020/06/image-16-193x288.png 193w, https://rebelscience.club/wp-content/uploads/2020/06/image-16-484x720.png 484w" sizes="(max-width: 536px) 100vw, 536px" /></a><figcaption class="wp-element-caption">Click to enlarge/download</figcaption></figure>
</div>


<p class="wp-block-paragraph">That&#8217;s it for this article. Now we know how to create and manipulate Strings in Rust. How to write a simple function, pass a parameter to it and return a value. We also learned how to add a module (crate) to Rust and include files into other files.</p>



<hr class="wp-block-separator has-text-color has-black-color has-css-opacity has-black-background-color has-background is-style-wide"/>



<h3 class="wp-block-heading">Links</h3>



<hr class="wp-block-separator has-text-color has-black-color has-css-opacity has-black-background-color has-background is-style-wide"/>



<ul class="wp-block-list">
<li>Rust String video: <a rel="noreferrer noopener" href="https://youtu.be/ClPrjjHmo2Y" target="_blank">https://youtu.be/ClPrjjHmo2Y</a></li>



<li>Additional Rust String methods: <a href="https://www.tutorialspoint.com/rust/rust_string.htm">https://www.tutorialspoint.com/rust/rust_string.htm</a></li>
</ul>



<p class="wp-block-paragraph"><strong>Recommended Rust programming book:</strong></p>


<div class="wp-block-image">
<figure class="aligncenter is-resized"><img decoding="async" src="https://images-na.ssl-images-amazon.com/images/I/71qj8wdDtjL.jpg" alt="Mastering Rust: Learn about memory safety, type system, concurrency, and the new features of Rust 2018 edition, 2nd Edition" width="230" height="284"/><figcaption class="wp-element-caption">Mastering Rust: Learn about memory safety, type system, concurrency, and the new features of Rust 2018 edition, 2nd Edition<br>(<a href="https://amzn.to/2TLd7Yt" target="_blank" rel="noreferrer noopener">UK</a> / <a href="https://amzn.to/2zCSSFI" target="_blank" rel="noreferrer noopener">US</a>)</figcaption></figure>
</div>


<p class="wp-block-paragraph"><strong>GitHub: <a href="https://github.com/rebelC0der/From_Python_To_Rust">https://github.com/rebelC0der/From_Python_To_Rust</a></strong></p>



<p class="wp-block-paragraph">Video version of the article:</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="From Python to Rust. Part 2: Strings, Functions &amp; Crates/Modules." width="640" height="360" src="https://www.youtube.com/embed/i957TYyN_SY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>
]]></content:encoded></item><item><title>From Python to Rust: Part 1.</title><link>https://rebelscience.club/2020/05/from-python-to-rust-part-1/</link><guid isPermaLink="true">https://rebelscience.club/2020/05/from-python-to-rust-part-1/</guid><pubDate>Sun, 17 May 2020 17:16:29 GMT</pubDate><description>In this series of articles, we will explore a young and very exciting programming language — Rust. We will see how Rust can help us
</description><content:encoded><![CDATA[
<p class="wp-block-paragraph">In this series of articles, we will explore a young and very exciting programming language — Rust. We will see how Rust can help us to speed up some of our existing and future Python code. Many agree, that the key features of Python are its simplicity and readability. Let’s try and see if we can have the same or similar simplicity and readability from Rust and get that incredible execution speed of a compiled language.</p>



<p class="wp-block-paragraph">While Python is an amazing, general purpose language and is super easy to write and understand, it might be too slow when we need to write an algorithm that needs to ‘crunch’ through a lot of data. Of course, well written Python code that uses something like NumPy or Cython, is still, very, very fast and probably enough in most cases. All the checks that are done by interpreted language like Python, will slow our code a lot.</p>



<p class="wp-block-paragraph">We will look at Python and Rust code side-by-side and attempt to port (rewrite) some of our Bioinformatics related code from Python to Rust while comparing code execution speed of both. We will see, that we don’t necessarily need/have to sacrifice simplicity of Python for Rust’s speed. And some functionality, written in Python, will stay in Python and just call our faster code, rewritten in Rust. This way, we will attempt to get a ‘sweet spot’ (best from both languages) to solve our Bioinformatics problems.</p>



<hr class="wp-block-separator has-text-color has-header-gradient-color has-css-opacity has-header-gradient-background-color has-background"/>



<h4 class="wp-block-heading">Prerequisites:</h4>



<ul class="wp-block-list">
<li>Good Python knowledge.</li>



<li>Basic Rust knowledge (I assume you are here because you know what you are doing) 😛</li>



<li>You understand the difference between compiled and interpreted language.</li>



<li>You understand the difference between statically and dynamically typed languages.</li>



<li>Code Editor with both, Python and Rust integrations.</li>
</ul>



<h4 class="wp-block-heading">Good to have:</h4>



<ul class="wp-block-list">
<li>Previous C-style (C-type?) language experience.</li>



<li>Desire to learn a new, exciting, compiled, memory safe and fast systems programming language.</li>
</ul>



<hr class="wp-block-separator has-text-color has-header-gradient-color has-css-opacity has-header-gradient-background-color has-background"/>



<p class="wp-block-paragraph">Make sure you have the latest Python version installed: <a href="https://www.python.org/downloads/" target="_blank" rel="noreferrer noopener">Link</a><br>Make sure you have the latest Rust/Cargo version installed: <a href="https://www.rust-lang.org/tools/install" target="_blank" rel="noreferrer noopener">Link</a></p>



<p class="wp-block-paragraph">We start by creating a folder, I called <code>py_rust</code>. In that, we create one folder &#8216;by hand&#8217;: <code>python</code> and add an empty file called <code>main.py</code>. This is where our Python code will live. For the Rust folder, we will use Rust&#8217;s project and package manager, <code>Cargo</code>. This will create a small project for us, with all the necessary files, needed to run and configure the Rust project. </p>



<p class="wp-block-paragraph">Start a prompt (bash/shell/cmd) in our newly created <code>py_rust</code> folder,&nbsp;which&nbsp;already contains Python and execute the following:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;shell&quot;,&quot;mime&quot;:&quot;text/x-sh&quot;,&quot;theme&quot;:&quot;mbo&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Shell&quot;,&quot;language&quot;:&quot;Shell&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;shell&quot;}">cargo new rust --bin</pre></div>


<p class="wp-block-paragraph">So parameters are:</p>



<p class="wp-block-paragraph"><code>new</code> &#8211; makes the cargo tool create a new project.<br><code>rust</code> &#8211; the name of the folder for the project.<br><code>--bin</code> &#8211; make the cargo tool create a project for a binary, not a library.<br><br>Now we should have the following structure:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;application/json&quot;,&quot;theme&quot;:&quot;mbo&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;JSON&quot;,&quot;language&quot;:&quot;JSON&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;json&quot;}">[py_rust]
├── python
│   └── main.py
└── rust
    ├── Cargo.lock
    ├── Cargo.toml
    ├── src
    │   └── main.rs
    └── target</pre></div>


<hr class="wp-block-separator has-text-color has-header-gradient-color has-css-opacity has-header-gradient-background-color has-background"/>



<p class="wp-block-paragraph">As Rust is a comparably young language, you might find tools and IDE integrations don&#8217;t work as well as say for Python, C++, Java. I am using VSCodium (VSCode) and it does have a good enough integration. Our goal here is to see two languages, Python and Rust, side-by-side, and be able to just use a keyboard shortcut to run both.</p>



<p class="wp-block-paragraph">Please make sure that you add Python and Rust project folders into our code editor one-by-one, and not the whole <code>py_rust</code> folder. This is because the Rust cargo system&nbsp;will be looking for a project source in a root directory, so if our root directory is <code>py_rust</code>, this will fail. Adding each folder separately will make sure that both, Python and Rust are executed <strong>not</strong> from <code>py_rust</code> but from their individual workspace. More details on that in my video version of this article.</p>



<p class="wp-block-paragraph">In the article <a rel="noreferrer noopener" href="https://rebelscience.club/2020/04/lets-set-up-a-code-editor-for-python-and-bioinformatics/" target="_blank">here</a>, we set up a <a href="http://vscodium.com" target="_blank" rel="noreferrer noopener">VSCodium</a> editor to be able to run Python as easy as possible, using just two plugins. If you have this configured already, you should, in theory, be able to run Rust exactly the same way. Make sure you have these two extensions installed:</p>



<figure class="wp-block-image size-full"><a href="https://rebelscience.club/wp-content/uploads/2020/05/816-795-max.png"><img decoding="async" width="816" height="795" src="https://rebelscience.club/wp-content/uploads/2020/05/816-795-max.png" alt="Rust Bioinformatics" class="wp-image-488" srcset="https://rebelscience.club/wp-content/uploads/2020/05/816-795-max.png 816w, https://rebelscience.club/wp-content/uploads/2020/05/816-795-max-296x288.png 296w, https://rebelscience.club/wp-content/uploads/2020/05/816-795-max-739x720.png 739w, https://rebelscience.club/wp-content/uploads/2020/05/816-795-max-768x748.png 768w" sizes="(max-width: 816px) 100vw, 816px" /></a><figcaption class="wp-element-caption">Click to enlarge/download</figcaption></figure>



<p class="wp-block-paragraph">The only thing we need to add is a <code>code runner</code> configuration for Rust.</p>



<p class="wp-block-paragraph">1. While you have <a href="http://vscodium.com" target="_blank" rel="noreferrer noopener">VSCodium</a> opened, hit <code>F1</code> and type <code>settings</code> and choose the first option:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://rebelscience.club/wp-content/uploads/2020/05/Screenshot_20200519_101928.png"><img decoding="async" width="776" height="103" src="https://rebelscience.club/wp-content/uploads/2020/05/Screenshot_20200519_101928.png" alt="" class="wp-image-487" srcset="https://rebelscience.club/wp-content/uploads/2020/05/Screenshot_20200519_101928.png 776w, https://rebelscience.club/wp-content/uploads/2020/05/Screenshot_20200519_101928-512x68.png 512w, https://rebelscience.club/wp-content/uploads/2020/05/Screenshot_20200519_101928-768x102.png 768w" sizes="(max-width: 776px) 100vw, 776px" /></a><figcaption class="wp-element-caption">Click to enlarge/download</figcaption></figure>
</div>


<p class="wp-block-paragraph">2. Add this line to your <code>settings.json</code> file:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;application/json&quot;,&quot;theme&quot;:&quot;mbo&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;wide&quot;,&quot;fileName&quot;:&quot;JSON&quot;,&quot;language&quot;:&quot;JSON&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;json&quot;}">&quot;code-runner.executorMap&quot;: {
	&quot;rust&quot;: &quot;if [ $(basename $dir) = 'examples' ]; then cargo run -q --example $fileNameWithoutExt; else cargo run -q; fi&quot;
}</pre></div>


<p class="wp-block-paragraph">Now we should be able to run both, Python and Rust with just a key combination (Ctrl + Alt + N).</p>



<hr class="wp-block-separator has-text-color has-header-gradient-color has-css-opacity has-header-gradient-background-color has-background"/>



<p class="wp-block-paragraph">Let&#8217;s add our first line of code and execute it:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;gruvbox-dark&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Python&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">print(&quot;Hello, I am Python!&quot;)</pre></div>

<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;gruvbox-dark&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">fn main() {
    println!(&quot;Hello, I am Rust and I am fast&quot;);
}</pre></div>


<p class="wp-block-paragraph">And now we can try executing the code and if everything is configured correctly, we should see this:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://rebelscience.club/wp-content/uploads/2020/05/image.png"><img decoding="async" width="659" height="194" src="https://rebelscience.club/wp-content/uploads/2020/05/image.png" alt="" class="wp-image-494" srcset="https://rebelscience.club/wp-content/uploads/2020/05/image.png 659w, https://rebelscience.club/wp-content/uploads/2020/05/image-512x151.png 512w" sizes="(max-width: 659px) 100vw, 659px" /></a><figcaption class="wp-element-caption">Rust output.</figcaption></figure>
</div>

<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://rebelscience.club/wp-content/uploads/2020/05/image-1.png"><img decoding="async" width="659" height="194" src="https://rebelscience.club/wp-content/uploads/2020/05/image-1.png" alt="" class="wp-image-495" srcset="https://rebelscience.club/wp-content/uploads/2020/05/image-1.png 659w, https://rebelscience.club/wp-content/uploads/2020/05/image-1-512x151.png 512w" sizes="(max-width: 659px) 100vw, 659px" /></a><figcaption class="wp-element-caption">Python output.</figcaption></figure>
</div>


<p class="wp-block-paragraph">And here is how our setup should look like:</p>



<figure class="wp-block-image alignwide size-full"><a href="https://rebelscience.club/wp-content/uploads/2020/05/image-2.png"><img decoding="async" width="1860" height="1057" src="https://rebelscience.club/wp-content/uploads/2020/05/image-2.png" alt="Rust Bioinformatics" class="wp-image-496" srcset="https://rebelscience.club/wp-content/uploads/2020/05/image-2.png 1860w, https://rebelscience.club/wp-content/uploads/2020/05/image-2-507x288.png 507w, https://rebelscience.club/wp-content/uploads/2020/05/image-2-1267x720.png 1267w, https://rebelscience.club/wp-content/uploads/2020/05/image-2-768x436.png 768w, https://rebelscience.club/wp-content/uploads/2020/05/image-2-1536x873.png 1536w" sizes="(max-width: 1860px) 100vw, 1860px" /></a><figcaption class="wp-element-caption">Project view. We can click-in to opened Python or Rust files and use (Ctrl + Alt + N) to execute each.</figcaption></figure>



<hr class="wp-block-separator has-text-color has-header-gradient-color has-css-opacity has-header-gradient-background-color has-background"/>



<p class="wp-block-paragraph">Now let&#8217;s start looking at the actual code.</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;gruvbox-dark&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Python&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">x = 100.0
y = 1.0

print(f&quot;x: {x}, and y: {y}&quot;)
y = y * -0.3145
print(f&quot;x: {x}, and y: {y}&quot;)</pre></div>

<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;gruvbox-dark&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">let x = 100.0;
let mut y = 1.0;

println!(&quot;x: {}, and y: {}&quot;, x, y);
y = y * -0.3145;
println!(&quot;x: {}, and y: {}&quot;, x, y);</pre></div>


<p class="wp-block-paragraph"><strong>Note</strong>: for Rust, we need to remember that all the code is wrapped in the <code>main() {}</code> function.</p>



<p class="wp-block-paragraph">We can see, that the code is very similar. Print statements differ just a bit, but easy to get used to. In Python, we use f-strings. But the difference, of course, is in how we declare variables. This is why Rust is statically typed. We need to tell it what type our variable is before we use it. The concept of mutable/immutable is present in both languages, but in Rust we need to specify <code>mut</code> if we plan to change the value of the variable somewhere in the code. So on the line <code>5</code> we modify the variable <code>y</code> and that is why we need it to be mutable. If we don&#8217;t declare it as <code>let mut</code> and try executing the code, we will see the beauty of Rust&#8217;s compiler:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;gruvbox-dark&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;wide&quot;,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">error[E0384]: cannot assign twice to immutable variable `y`
 --&gt; src/main.rs:8:5
  |
5 |     let y = 1.0;
  |         -
  |         |
  |         first assignment to `y`
  |         help: make this binding mutable: `mut y`
...
8 |     y = y * -0.3145;
  |     ^^^^^^^^^^^^^^^ cannot assign twice to immutable variable

error: aborting due to previous error

For more information about this error, try `rustc --explain E0384`.
error: could not compile `rust`.

To learn more, run the command again with --verbose.</pre></div>


<p class="wp-block-paragraph">We can see, that Rust compiler tells us&nbsp;<strong>exactly&nbsp;</strong>what is wrong. I wish all languages had such a helpful output.</p>



<hr class="wp-block-separator has-text-color has-header-gradient-color has-css-opacity has-header-gradient-background-color has-background"/>



<p class="wp-block-paragraph">Let’s see how&nbsp;<code>if</code>&nbsp;and&nbsp;<code>else</code>&nbsp;look like in both:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;gruvbox-dark&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Python&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">if y &lt; x:
    print(f&quot;The difference is: {x-y}&quot;)
elif y == x:
    print(f&quot;The difference is: {x-y}&quot;)
else:
    print(f&quot;The difference is: {y-x}&quot;)</pre></div>

<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;gruvbox-dark&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">if y &lt; x {
    println!(&quot;The difference is: {}&quot;, (x - y));
} else if y == x {
    println!(&quot;The difference is: {}&quot;, (y - x));
} else {
    println!(&quot;The difference is: {}&quot;, (y - x));
}</pre></div>


<p class="wp-block-paragraph">We can see that the code is almost identical. C-style language programmers probably will be tempted to wrap <code>y &lt; x</code> in <code>(y &lt; x)</code>. Let&#8217;s try doing that and see what Rust will tell us.</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;gruvbox-dark&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;wide&quot;,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">warning: unnecessary parentheses around `if` condition
  --&gt; src/main.rs:10:8
   |
10 |     if (y &lt; x) {
   |        ^^^^^^^ help: remove these parentheses
   |
   = note: `#[warn(unused_parens)]` on by default</pre></div>


<p class="wp-block-paragraph">Well, what can I say? Beautiful! Learning Rust with such amazing help from the compiler is pure joy.</p>



<hr class="wp-block-separator has-text-color has-header-gradient-color has-css-opacity has-header-gradient-background-color has-background"/>



<p class="wp-block-paragraph">Loops will look very similar:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;gruvbox-dark&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Python&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">x = 5
while x &gt; 0:
    print(f&quot;x is {x}&quot;)
    x -= 1

for i in range(3, 7):
    print(f&quot;i is {i}&quot;)</pre></div>

<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;gruvbox-dark&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">let mut x = 5;
while x &gt; 0 {
    println!(&quot;x is {}&quot;, x);
    x -= 1;
}

// Version 1 (Very Pythony):
for i in 3..7 {
    println!(&quot;i is {}&quot;, i);
}

// Version 2 (If you need to create a range on the fly):
let num_range = 3..7;
for i in num_range {
    println!(&quot;i is {}&quot;, i);
}</pre></div>


<p class="wp-block-paragraph">While/For loops and range usage are almost identical. The only difference is if you want to re-use the <code>x</code> variable in Python, you just overwrite it. This is where we can see that Python is <strong>not</strong>, and Rust <strong>is</strong> type-safe and does not allow you to just re-use a variable and requires something called <code>variable shadowing</code> on the line <code>1</code>. This is needed to protect <strong>you</strong> from writing broken code. Originally, we declared <code>x = 100.0</code>, and Rust interpreted it as a <code>float</code>. Now, if we just try overwriting it as <code>x = 5;</code> Rust will tell us that the original variable was <code>float</code> and now you are trying to assign an <code>integer</code> to it. Try doing that yourself and see what Rust compiler will tell you.</p>



<hr class="wp-block-separator has-text-color has-header-gradient-color has-css-opacity has-header-gradient-background-color has-background"/>



<p class="wp-block-paragraph">Let&#8217;s take a look at a List/Vector and how we can get an iterator and enumerator out of both:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;gruvbox-dark&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Python&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">tmp_lst = ['DNA', 'RNA', 'mRNA']

for value in tmp_lst:
    print(f&quot;value is {value}&quot;)</pre></div>

<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;gruvbox-dark&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">let tmp_vec = vec![&quot;DNA&quot;, &quot;RNA&quot;, &quot;mRNA&quot;];

for value in tmp_vec {
    println!(&quot;value is {}&quot;, value);
}</pre></div>


<p class="wp-block-paragraph">This is easy. What in Python is a List, is a Vector in Rust. We should see this output from both:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Python&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">value is DNA
value is RNA
value is mRNA</pre></div>


<p class="wp-block-paragraph">Now, if Python will allow accessing/modifying our List after we access it in a For loop, Rust will not allow us to do the same to its Vector. After both loops, try acceding/printing just the first element of a List/Vector: like this:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}"># Python:
print(tmp_lst[0])

// Rust:
println!(&quot;{}&quot;, tmp_vec[0]);</pre></div>


<p class="wp-block-paragraph">And now Rust will introduce us to yet another concept of <a rel="noreferrer noopener" href="https://dev.to/itnext/rust-ownership-and-borrowing-i2n" target="_blank">Ownership and Borrowing</a>, also (<a rel="noreferrer noopener" href="https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html" target="_blank">here</a>)</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;gruvbox-dark&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;wide&quot;,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">error[E0382]: borrow of moved value: `tmp_vec`
  --&gt; src/main.rs:34:20
   |
26 |     let tmp_vec = vec![&quot;DNA&quot;, &quot;RNA&quot;, &quot;mRNA&quot;];
   |         ------- move occurs because `tmp_vec` has type `std::vec::Vec&lt;&amp;str&gt;`,
   | 	                                 which does not implement the `Copy` trait
27 |     for value in tmp_vec {
   |                  -------
   |                  |
   |                  value moved here
   |                  help: consider borrowing to avoid moving into the for loop: `&amp;tmp_vec`
...
34 |     println!(&quot;{}&quot;, tmp_vec[0]);
   |                    ^^^^^^^ value borrowed here after move</pre></div>


<p class="wp-block-paragraph">If you never heard about this Rust concept, you should invest your time in reading about it. Basically, after we provided our <code>tmp_vec</code> Vector to a For loop in Rust, we gave the <code>ownership</code> of our <code>tmp_vec</code> Vector to that For Loop. For loop did what we asked it to do, which is to print the contents of that Vector, and after that, <code>tmp_vec</code> was discarded as our For loop <code>owned</code> it. After the For loop was done and out of scope, everything in the scope of that For loop is now gone too.</p>



<p class="wp-block-paragraph">This is easily &#8216;fixed&#8217; by &#8216;asking&#8217; our <code>tmp_vec</code> to return just the iterator, and not itself: <code>tmp_vec.iter()</code>, and now line 7 will not produce an error:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;gruvbox-dark&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">let tmp_vec = vec![&quot;DNA&quot;, &quot;RNA&quot;, &quot;mRNA&quot;];

for value in tmp_vec.iter() {
    println!(&quot;value is {}&quot;, value);
}

println!(&quot;{}&quot;, tmp_vec[0]);</pre></div>


<hr class="wp-block-separator has-text-color has-header-gradient-color has-css-opacity has-header-gradient-background-color has-background"/>



<p class="wp-block-paragraph">And now let&#8217;s add an enumerator to our For loop:</p>


<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;gruvbox-dark&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Python&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">tmp_lst = ['DNA', 'RNA', 'mRNA']

for pos, value in enumerate(tmp_lst):
    print(f&quot;value at pos {pos} is {value}&quot;)</pre></div>

<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;rust&quot;,&quot;mime&quot;:&quot;text/x-rustsrc&quot;,&quot;theme&quot;:&quot;gruvbox-dark&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;Rust&quot;,&quot;language&quot;:&quot;Rust&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;rust&quot;}">let tmp_vec = vec![&quot;DNA&quot;, &quot;RNA&quot;, &quot;mRNA&quot;];

for (pos, value) in tmp_vec.iter().enumerate() {
    println!(&quot;value at pos {} is {}&quot;, pos, value);
}</pre></div>


<p class="wp-block-paragraph">Almost identical. Alright. This is it for this article. See you in the next one soon.</p>



<p class="wp-block-paragraph">All the code is available her: <a href="https://github.com/rebelC0der/From_Python_To_Rust">https://github.com/rebelC0der/From_Python_To_Rust</a></p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="From Python to Rust. Part 1" width="640" height="360" src="https://www.youtube.com/embed/Ygk0IMbu2nY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div><figcaption class="wp-element-caption">Video version of this article.</figcaption></figure>
]]></content:encoded></item></channel></rss>