Posts

Showing posts from December, 2022

Borrowing In Rust

Image
In this article, we will learn about borrowing in Rust. In Ownership In Rust , we have learned that only a single variable can hold the ownership of data on the heap at a time. Before starting the discussion of borrowing, we should understand that assigning a variable to another variable, passing a variable as an argument to a function, and assigning the return value of a function to a variable are the same. Another concept of scope is also very important. In Rust, the last use of a variable defines the scope of the variable. In other words, the scope of a variable ends when it is used the last time in a function. When we assign a variable that points to data on the heap to another variable, it transfers ownership of the data to another variable. As we have read above, ownership is also transferred in the case of an argument passing to a function and returning a value from the function. To get rid of the situation, where ownership is transferred to a function and again re...

Ownership In Rust

Image
    In this article, we will learn about ownership in Rust. fn main () {     let i = 5 ; //on stack     let j = i ; //on stack     println! ( "i = {i}, j = {j}" );       let str = String :: from ( "theloveoftechI" );     let str1 = str . clone ();     println! ( "{str}, {str1}" );       let mv_str = str ;     println! ( "{mv_str}" );     //println!("{str}"); //This is problematic }   Variables are allocated on the stack or on the heap. We can only push an item on the top of the stack. We can also pop an item from the top of the stack. Variables on the stack have fixed sizes. All variables are allocated on the stack when a function is called. In the case of a heap, space is allocated based on the size of the data. If we want to grow a particular vegetable in the garden, so we reserve a certain area for that vegetable. In the case of i and j, both are on the stack ...