<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Varun Doshi</title>
    <description>The latest articles on Forem by Varun Doshi (@varun-doshi).</description>
    <link>https://forem.com/varun-doshi</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1195228%2Fd4585b37-a8df-48b3-9fee-1d2e9fb05191.jpg</url>
      <title>Forem: Varun Doshi</title>
      <link>https://forem.com/varun-doshi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/varun-doshi"/>
    <language>en</language>
    <item>
      <title>Rust Ownership 101</title>
      <dc:creator>Varun Doshi</dc:creator>
      <pubDate>Mon, 27 Nov 2023 05:47:09 +0000</pubDate>
      <link>https://forem.com/varun-doshi/rust-ownership-101-3epm</link>
      <guid>https://forem.com/varun-doshi/rust-ownership-101-3epm</guid>
      <description>&lt;p&gt;One of the most common pitfalls that Rust beginners face is the &lt;strong&gt;Ownership concept&lt;/strong&gt;. It is a set of crucial yet simple rules that makes Rust so popular. However, it is quite divergent from how other languages handle similar situations.&lt;/p&gt;

&lt;p&gt;In this article, we’ll go over what the Ownership model means exactly, some of its nuances and see how Rust handles memory compared to other languages.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxg9ay903ewxw4owpvtjb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxg9ay903ewxw4owpvtjb.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The Ownership Model
&lt;/h2&gt;

&lt;p&gt;Let's get to the crux of the issue. The 3 rules that govern Ownership in Rust:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Each value in Rust has an owner.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;There can only be one owner at a time.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When the owner goes out of scope, the value will be dropped.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you keep these in mind, you’re already halfway to understanding how Ownership works in Rust.&lt;/p&gt;

&lt;h2&gt;
  
  
  Deep Dive
&lt;/h2&gt;

&lt;p&gt;Let’s look at how other programming languages handle memory:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Garbage Collector&lt;/strong&gt;: In Java or C#, the programmer does not have control over memory and it's handled by a dedicated Garbage collector. Makes your life easier, but takes away fine-grain control.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Manual Memory Management&lt;/strong&gt;: In C or C++, programmers have to manually allocate/deallocate memory. This can cause a lot of errors and bugs, especially from a security point of view.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;And then there’s the &lt;strong&gt;Ownership Model&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now that you understand these forms, it’ll be easier to grasp how the memory in Rust works.&lt;/p&gt;

&lt;p&gt;2 essential concepts to keep in mind.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Stack &lt;/strong&gt;— Memory location available to our program that works on a LIFO(Last In First Out) basis. This means the data that entered last, will be removed first. Think of it like a stack of books. All data stored here have fixed size during compile-time.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Heap &lt;/strong&gt;— Variables whose size is not known at compile time are stored here among others. In most cases, variables stored in the stack have a pointer attached to the actual value in the heap.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0i56dokcpcpool3qlav2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0i56dokcpcpool3qlav2.png" alt="Stack &amp;amp; Heap"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Scope
&lt;/h2&gt;

&lt;p&gt;Scope is a term often used in programming to denote a specific portion between which a variable lives. Outside this portion, the variable is non-existent.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main() {
   {      //scope starts
       let a:i32=5;
       println!("{}",a);      //prints 5  
   }      //scope ends
// 'a' does not exist here

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

&lt;/div&gt;



&lt;p&gt;So the value of the variable a is dropped automatically once the scope in which it was declared in is over.&lt;/p&gt;

&lt;h2&gt;
  
  
  Copy &amp;amp; Move
&lt;/h2&gt;

&lt;p&gt;Data stored in the stack can be copied to another variable. However, data stored in the heap cannot be copied; it can be “moved”. This means the ownership of that piece of data is changed.&lt;/p&gt;

&lt;p&gt;This code will throw an error. Here’s why:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main() {
    let a:i32=5;
    let b:i32=a;
    let s1 = String::from("Hello World");
    let s2 = s1; // Ownership transferred or 'moved'

    println("{}",a);        //prints 5
    println("{}",b);        //prints 5
    // Error: 's1' no longer accessible
    println!("{}", s1);
    //will print "Hello World"
    println!("{}", s2);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; are stored in the stack since their sizes are known i.e. 32 bits. So, the value of a can be copied into &lt;code&gt;b&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;However, &lt;code&gt;s1&lt;/code&gt; is stored in the heap and this means it cannot be copied. When we assign the value of &lt;code&gt;s1&lt;/code&gt; to &lt;code&gt;s2&lt;/code&gt; ,we are moving the pointer from &lt;code&gt;s1&lt;/code&gt; to &lt;code&gt;s2&lt;/code&gt;. Thus, &lt;code&gt;s1&lt;/code&gt; no longer points to “Hello World”&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjyp72of69w3kncqoba02.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjyp72of69w3kncqoba02.png" alt="moved value"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;But why can’t you copy data from the heap, you may ask?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If we think back to the differences between the stack and heap, we remember that the size of data stored on the heap is not known at compile time, which means we need to run through some memory allocation steps during runtime. This can be expensive. Depending on how much data is stored, we could quickly run out of memory if we keep making copies of data without caution.&lt;/p&gt;

&lt;h2&gt;
  
  
  Does this mean we can NEVER copy heap data?
&lt;/h2&gt;

&lt;p&gt;The answer is &lt;strong&gt;No — You can copy heap data&lt;/strong&gt;, but it comes with consequences. There’s a handy method &lt;code&gt;clone()&lt;/code&gt; that helps you do exactly that. But this will create a deep copy, which means it will allocate the same data again to the heap. As stated, memory allocation/deallocation in the heap is slower than the stack and thus more expensive. Hence, clone() comes with performance issues.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsyeno1shpo93vd3cvmm1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsyeno1shpo93vd3cvmm1.png" alt="Clone"&gt;&lt;/a&gt;&lt;br&gt;
Hence, the following code will run successfully&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main() {
    let s1 = String::from("Hello World");
    let s2 = s1.clone();    //Deep clone

    // Will print "Hello World"
    println!("{}", s1);
    //  Will print "Hello World"
    println!("{}", s2);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Borrowing and Referencing
&lt;/h2&gt;

&lt;p&gt;Let's look at another concept — &lt;strong&gt;Borrowing&lt;/strong&gt;. It allows us to use another variable’s data without having to copy it. Borrowing creates a pointer to the variable whose data we want.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main() {
    let s1 = String::from("Hello Rust");
    let s2 = &amp;amp;s1;        //Borrowing value of s1(immutable)

    // Will print "Hello Rust"
    println!("{}", s1);
    //  Will print "Hello Rust"
    println!("{}", s2);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F35xcb95wxeskn9nkyurt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F35xcb95wxeskn9nkyurt.png" alt="borrowing"&gt;&lt;/a&gt;&lt;br&gt;
Rust allows multiple immutable references to be alive at the same time. This is called read-only referencing. However, only 1 mutable reference can be alive at a particular point in time. This ensures memory safety and prevents read-write errors or data races.&lt;/p&gt;

&lt;p&gt;But keep in mind, if the original variable goes out of scope or its value is moved, the borrowed value will be dropped as well.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main() {
    let  s1 = String::from("Hello Rust");
    {
        let s2 = &amp;amp;s1;
        println!("{}", s2);     //Will print "Hello Rust"
        let s3 = s1;
        println!("{}", s2);     //Will throw error value of s1 is moved
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwgxxf63nxawsk9v947sm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwgxxf63nxawsk9v947sm.png" alt="cloning"&gt;&lt;/a&gt;&lt;br&gt;
Initially, &lt;code&gt;s2&lt;/code&gt; points to &lt;code&gt;s1&lt;/code&gt; and its value is owned by &lt;code&gt;s1&lt;/code&gt; itself. When &lt;code&gt;s3&lt;/code&gt; is initialized, the value is moved from &lt;code&gt;s1&lt;/code&gt; to &lt;code&gt;s3&lt;/code&gt; . Now, &lt;code&gt;s2&lt;/code&gt; is still pointing to &lt;code&gt;s1&lt;/code&gt; ,but there is no value associated with &lt;code&gt;s1&lt;/code&gt; .Hence, it will throw an error if you try to use either &lt;code&gt;s1&lt;/code&gt; or &lt;code&gt;s2&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;That’s it for this post. I hope you have a better understanding of what the Ownership Model is and how Memory is managed in Rust.&lt;/p&gt;

&lt;p&gt;For more informative posts, follow me on &lt;a href="https://twitter.com/Varunx10" rel="noopener noreferrer"&gt;&lt;strong&gt;Twitter&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Thank you for reading 🎉&lt;/p&gt;

</description>
      <category>rust</category>
      <category>programming</category>
      <category>softwaredevelopment</category>
      <category>development</category>
    </item>
  </channel>
</rss>
