Skip to main content

What is Rust Ownership?

 What is Rust Ownership?

Ownership concept 
Memory and Allocation
  • Data can be stored either in stack or heap memory in Rust.

Memory Types

  1. Stack Memory
  2. Heap Memory

Stack and Heap

Stack and Heap are parts of memory to be used at runtime, but they are structured in different ways.

Stack

Stack rust ownership

 It collects values in the order it get them and removes the values in the opposite order. Referred to as Last In, First Out (LIFO).
 

Stack: Think of a stack of plates

Stack rust ownership

When we put more plates,we add them on the top of the pile, and when we required a plate, we take one off the top. Putting or removing plates from the middle or bottom wouldn't work as well.
 
  • Adding data is called pushing onto the stack 
  • Removing data is called popping off the stack. 
  • Stack memory is an organized memory. 
  • It is more faster than the heap memory due to the way it accesses the memory. 
  • All data gathered on the stack must have a known, fixed size
 

Stack Push and Pop Example:

 

 

Stack rust ownership


 
Stack rust ownership


Stack: in action

 

Stack rust ownership

 

Stack: How it works?
  • The code when calls a function, the values moves into the function (including, potentially, pointers to data on the heap) and the function’s local variables get pushed onto the stack. 

  • When the function is end, those values get popped off the stack.

 
  

  • The Heap is Less Organized.
  • Requested from OS.
  • Slower.
  • Follow pointer.
  • Huge amount...take time to mange data in the heap. 
  • The Data with a size that is unknown at compile time or a size that might change must be kept on the heap.
Heap rust ownership

 

Heap: Allocation


  • When we put data on the heap, we say for some amount of space from OS.  
  • The operating system gets an empty spot in the heap that is big enough, marks it as being in use, and returns a pointer, which is the address of that location. 

Because the operating system has not to search for place to store new data;that location is always at the top of the stack.

 

Why accessing data to the heap is more slow than allocating on the stack ?

Allocating space on the heap needs more work,because you ask for some amount of space to operating system every time. OS has to follow the pointer every time.

 

Ownership

  • All programs have to find the way they use a computer’s memory while running.
  • Some languages have kept garbage collection that constantly looks for no longer used memory as the program runs.  
  • The programmer must explicitly allocate and free the memory in other languages.
  • Rust uses a third approach wherein memory is kept through a system of ownership.
  • Ownership is managed with a set of defined rules that the compiler checks at compile time.
  • No one of the ownership features slow down our program while it’s running. 

    In simple words for understanding purpose…… 

    • Ownership is the forwaring of currently possessed entity to another party which causes the previous owner to no longer have access to the object that is being transferred. 
    • There are very clear rules about which piece of code owns a resource in Rust.
    • It’s the block of code that created the object representing the resource in the simplest case.
    • In the last of the block the object is destroyed and the resource is released.
     
  • Example 

    fn main()
    {// s is not valid here, 

    it’s not yet declared
        let s = "hello";
        // s is valid from this point forward
        // do stuff with s
        println!("{}", s);
    }// 

    This scope is finishes, and s is no longer valid

     

    In this example the letter or variable “s” is the owner of the word “hello” and is valid from the point of declaration after the start of the parenthesis “{“ 

    and it exist valid until the end of the parenthesis “}”.

     

     The Rust’s unique feature is ownership which enables it to make memory safety guarantees without needing a garbage collector.

    Why Ownership 

    • Maintaining record of what parts of code are using what data on the heap, minimizing the amount of duplicate data on the heap, and cleaning up unused data on the heap for that we don’t run out of space are all problems that ownership addresses. 
    • All primitive data types (integers, booleans, string literals) and pointers (address of heap data) are stored and kept on stack whereas for more complicated data types we have heap.

    Ownership Rules

  Rule # 1
 
 Each value in Rust has a variable that's known its owner.
 
Example
  • let a = “Hello world!”;

      ↙ ↘


    Variable Value

     

     In this example the variable i.e "a" is also the owner of the value "Hello world!".


    Rule # 2

     

    There must only be one owner at a time 

     

    Example

     

    let b = String::from(“Hello”);     –> here variable “b” is the owner

    let c = d;            –> here the value of “c” is moved to                       variable “d” which now becomes     the owner of “Hello

    Understanding both variables “a” and “b” are within the same scope.

     

     Rule # 3

     

    When the owner went out of scope, so does the value  

     

     Example 

     

    fn main() {

        {                       

     –> “b” is not valid here, it’s not yet declared

            let a = “Hello";      

     –> “b” is valid from this point forward

                    –> do stuff with “b”

        }                

     –> this scope is now over and “b” is no longer valid

    }

    For more detail click

     

Popular posts from this blog

What is Internet of Things (IoT)?

 What is Internet of Things (IoT)?    The internet of Things, or IoT, refers to the billions of physical devices  round the  world that are now connected to  the web  , collecting, sharing and analyses  of knowledge  . It presents and provides the explanation of the network of physical things which is embedded with software , sensors,  and other technologies for the benefit of connecting and exchanging data with other devices and systems on the internet   . Due to the cheap processors and wireless networks, it's possible to  means  anything, from a pill to an aero plane to a self-driving car into  an area  of the IoT. Overview IoT will control the Fourth  technological revolution  . The Fourth  technological revolution  is changing the very software-defined automation allows manufacturers to link all stages of  the worth  chain, rapidly adapt to changing markets , and make highly personalized products on a mass scale. The opportunities provided by this revolution are authenticated

What is Rust Borrowing?

What is Rust Borrowing? Borrowing We call having references as function parameters borrowing. As in real world , if an individual owns something, we 'll borrow it from them . Whenever we’re done, we 've got to offer it back. Referencing  The reference is that the act of consulting somebody or something so as to urge information We would  declare reference in terms of Rust programing as if we are taking a replica of it without damaging or taking its ownership. ‘&’ symbol is employed to pass the reference Have a look that  how ‘&’ symbol is employed in code. fn main() { let s1 = String::from("hello"); let len = calculate_length(&s1); println!("The length of {} is {}.", s1, len); } fn calculate_length(s: &String) -> usize { s.len()} Mutable References The actual concept of mutable reference is same as we use mutable variable When  we  need to  modify  mutable reference is employed once   the worth we make regard to.

Kubernetes Readiness Probes

 Kubernetes Readiness Probes Description We understand that liveness probes and the way they assist keep our apps healthy by ensuring unhealthy containers are restarted automatically. Same like liveness probes, Kubernetes permit us to also define a readiness looked for our pod. The readiness probe is deployed periodically and examines whether the precise pod should receive client requests or not. Whenever a container’s readiness probe returns back success, it’s signaling that the container is ready to simply accept requests. This notion of being prepared is clearly something that’s specific to every container. Almost as liveness probe Kubernetes sends requests to container and supported the result either successful or unsuccessful response it decides container is prepared to require traffic or still preparing for that. The liveness probes not like, if a container fails the readiness check, it won’t be killed or restarted.   This is a very good practice to