The Relation between “Rust and Safe Programming” !!

Reading Time: 5 minutes

The Rust programming language is a multi-paradigm programming language design for performance and safety, especially safe concurrency. It is syntactically similar to C++ but can guarantee memory safety by using a borrow checker to validate references. Rust achieves memory safety without garbage collection, and reference counting is optional.

safe and unsafe

Let’s talk about it –

Developers mostly care about Performance while building the code they usually don’t care much about how much space is used by the code but more importantly, these details became a matter of correctness when interfacing directly with the hardware, operating systems, or other languages.

When implementations details start to matter in a safe programming language.

  • Encourage the compiler/runtime to perform optimization
  • Rewrite the implementation in a language that lets you deal with those details
And for the rewrite option programmer mostly use C language but it is incredibly unsafe to use.

Here comes our Rust…

The rust programming language

The first thing is unlike C, Rust is a safe programming language, and like C it also an unsafe programming language.

Confused here… 🙂

Yes, More accurately Rust is both a Safe and Unsafe programming language. It can be considered as a combination of two programming languages Safe Rust and Unsafe Rust.

Ok, so safe rust provides safety but unsafe do not although the rust author advice not to use unsafe (code) rust but we can..!!

If you use Safe Rust then you will never have to worry about type safety or memory safety, you will never endure a dangling pointer or any other kind of undefined behaviour.

Using a standard library (which provides utilities) you can write high-performance applications.

Unsafe Rust

**Unsafe Rust is like Safe Rust with all the same rules. In addition, it just provides you some superpowers that are not safe according to Rust rules. It also does not guarantee memory safety.

Why and When Unsafe Rust is used ??

When the compiler tries to determine whether or not the code upholds the guarantee, then it’s better for it to reject some valid program rather than accept some invalid program. Although the code might be valid but if the compiler is not confident about it, it will reject the code.

So in such cases, you can use unsafe code to convey to the compiler that it can trust your code. But remember the risk is yours because if it’s incorrect then it can generate problems.

You can use an unsafe keyword and then start a new block that holds the unsafe code.

Operations you can perform with Unsafe Rust
  • Dereference a raw pointer
  • Call an unsafe function or method
  • Access or modify a mutable static variable
  • Implement an unsafe trait
  • Access fields of unions

Now let’s talk about Safe Rust

How does Safe Rust enforce safety?
Safety Rust

Safety is the main feature of the Rust Programming Language, it is embedded inside the Rust.
Such as being immutable per default and variables cannot lack a value (there is any null, so no Null Reference Exception).

Rust provides Memory Safety

Rust provides the solution for the problems like Buffer Overflow or the Dangling Pointer. Many languages like Java, Ruby provide automatic garbage collectors for such problems but Rust has a different way to deal with such problems. We need to know about the Ownership and Borrowing concept to know Memory Safety in Rust and how Rust does Memory Management.


Ownership

Ownership work as an elegant middle-ground between the manual memory control of C and the automatic garbage collector of Java.

In Rust, the memory space is own by the variable and this variable is the owner of that space and value. Now if any other variable wants to take that value then it can only take the reference of the value using & symbol (it cannot become the owner of that value). This is the Ownership rule of Rust.

For instance- If A is the owner of the shop and B wants to use that shop for a few months or weeks then B is just Borrowing that shop to carry out his work for that particular period. This doesn’t mean that B becomes the owner of the shop.

This Borrowing feature is similar to taking Reference in Rust. We take reference using & symbol and this reference and borrowing contribute to making Rust Safer.

Here in this below code number_1 is the Owner of value 5 and number_2 is taking Reference using “&”.
let number_1 = 5;
let number_2 = &number_1;

This allows Rust to achieve memory safety at compile-time, without relying on the garbage collector.
Rust uses explicit sources for memory management as garbage collection and that source is ownership which is checked by the compiler at compile time.

**Using this you will make your code safe and efficient.


Rules for Ownership
  1. Variables are owners of the value.
  2. Only one owner can be possible.
  3. When the owner gets out of scope value gets dropped.

Value is valid
A value or variable is valid from the point it is declared to the end of its scope.
    {                      // s is not valid here, it’s not yet declared
        let s = "hello";   // s is valid from this point forward

        // do stuff with s
    }                      // this scope is now over, and s is no longer valid
**Rust doesn’t use a memory collector it automatically frees up the memory as the variables go out of scope.

What else Rust has?

Why should we choose Rust?

Let’s talk about the Performance we get using the Rust programming language.

Performance

As we learn till now Rust language does not support a garbage collector. As it works in a way that it automatically finds out when the variable is out of scope or when its life ends at compile-time only and hence it automatically free up the memory.
This improves the Performance of Rust language at runtime that is the reason along with other languages Rust is also included in the System Programming Language.

The Compiler of Rust is so good that it find out most of the errors at compile-time only and provide more safety and better performance to the code.

We can also use Rust in Embedded Programming, why Rust for Embedded?? Check out this blog to know more.

If you want to read more content like this?  Subscribe to Rust Times Newsletter and receive insights and latest updates, bi-weekly, straight into your inbox. Subscribe to Rust Times Newsletter: https://bit.ly/2Vdlld7.

Rust times

Written by 

Nitin is a Software Consultant, with experience of more than 1.4 years. He works on Rust Programming Language and Embedded Development using Rust. He is also fond of Java Programming & Artificial Intelligence. Apart from that, his hobbies are Watching Netflix, Reading, Singing & Writing.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading