Today I am going to explain about a new programming language which is sponsored by Mozilla Research.
These are the topics and agenda of this article. You will get enough knowledge to write code in this programming language reading this article. As I always do, I am also sharing some basic code to get the idea of programming language.
- What is Rust?
- Why should I use Rust?
- Install Rust with rustup
- Cargo – Rust’s awesome package manager
- rustfmt – the Rust source code formatting tool
- Play with Rust: A short demo
- Datatype in Rust
- OwnerShip and Borrowing in Rust
What is Rust?
Rust is a new systems programming language designed for safety, concurrency, and speed. It was originally conceived by Graydon Hoare and is now developed by a team in Mozilla Research and the community.
Rust is blazingly fast and prevents almost all crashes. Rust is a Multi-paradigm, Functional, imperative, object-oriented programming language. It has Low-level and targets the same problem-space as C and C++ languages. Also, it is safe and pointer lifetimes guard against a lot of errors.
Rust provides memory safety and prevents segment fault and that is the same thing java provides. So what’s the difference? One thing which makes Rust programming language different from Java is ownership and borrowing concept. This programming language writes the particular value whatever you assign to the variable. It owns by that value only. You can’t use that. Once it is out of the box, is automatically destroyed.
I should probably call this language is “Ownership Oriented Language”. This is my own definition which is I actually observed in this language.
Why do we need a new system programming language?
Rust is open source System Programming language.A programmer doesn’t jump to another programming language if there are no advantages to use. Following points explain you that very well.
- State or art programming language.
- Solves a lot of common system programming bugs.
- Cargo : Rust Package manager
- Improving your toolkit
- Self learning
Why should use Rust
Rust is a good choice when you’d choose C++. You can also say, “Rust is a systems programming language that pursuing the trifecta: safe, concurrent, and fast.” I would say, Rust is an ownership-oriented programming language.
Every language has some pro and cons and people choosing a language based on the requirement so every time before you choose any language, you need reasons for choosing the specific one. Here, the reason that I’ve looked into Rust at first.
- Rust is new enough that you can write useful stuff that would have already existed in other languages. You can see Rust has a shorter learning curve. Rust doesn’t require any prior programming language. If you are newbie, you can easily digest Rust.
- It gives a relatively familiar tool to the modern C++ developers, but in the much more consistent and reliable ways.
- It is low-level enough that you take account of most resources.
- It’s more like C++ and Go programming language, less like Node and Ruby
- cargo is awesome. Managing crates just works as intended, which makes a whole lot of troubles you may have in other languages just vanish with a satisfying poof.
- System programming language
- Has great control like C/C++
- Safety and expressive like python.
Every programming language has some unique features so first understand those feature once before you chose for your development. After you know these much about language, this is a time to set up the language.
How to install Rust?
There are three ways to setup Rust Programming language.
- Prebuilt binaries are available at http://www.rust-lang.org/
- Source code is available from GitHub https://github.com/mozilla/rust
- Kits and resources are available from Rust India GitHub https://github.com/RustIndia/Rust
It source code is available because it is open source programming language.
How to Install Rust with Rustup
If you want to develop an application, set up the programming language is the first step to go. First of all, go to rustup.rs and this is automatically recognize your operating system and suggest steps as per that.
Ubuntu / MacOS
Open your terminal (Ctrl + Alt +T). Enter the following command
1 2 3 |
If you get any error while installing Rust, you can ask your queries on Rust channel #rust-beginners which you can find out on that link rustup.rs. Rust team will definitely reply over there to fix your error.
After installing Rust, check the version.Here is the command:
1 2 3 | rustc --version |
This is about Linux or Mac Installation. Let’s see Windows installation
Windows Installation
If you are using windows system and want to install Rust in windows, here is the step:
Go to https://win.rustup.rs/
Once you open the URL, it will directly recognize the operating system you are using and give the option to install package.
This will download the rustup-init.exe file. Once file downloaded, Double click and start the installation. That’s very easy!!
Best things about Rust
- Strong type system and reduces a lot of common bugs in system programming langyage
- Borrowing and Ownership which provides Memory safety and Freedom from data races
- Zero Cost abstraction
What is Cargo and how it works?
One of the best thing about Rust is Cargo. Cargo is the Rust Package Manager(RPM). Nowadays, you can see every language provides package manager using which you can configure and manage packages. It is a tool that allows Rust projects to declare their various dependencies and ensure that you’ll always get a repeatable build.
To accomplish this goal, Cargo does four things:
- Introduces two metadata files with various bits of project information.
- Fetches and builds your project’s dependencies.
- Invokes rustc or another build tool with the correct parameters to build your project.
- Introduces conventions to make working with Rust projects easier.
If you want to submit your code to Rust community and other uses your package for that you can submit it to cargo.
How to create a new project?
Open the URL https://crates.io/.
Rustfmt
A tool for formatting Rust code according to style guidelines
How to write a code in Rust with example?
A web interface for running Rust code. The interface can also be accessed in most Rust-related channels on irc.mozilla.org. To use Playbot in a public channel, address your message to it.
1 2 3 4 5 6 | playbot: println!("Hello, World"); -playbot:#rust-offtopic- Hello, World -playbot:#rust-offtopic- () playbot: 1+2+3 -playbot:#rust-offtopic- 6 |
You can also private message Playbot your code to have it evaluated. In a private message, don’t preface the code with playbot’s nickname:
1 2 3 | /msg playbot println!("Hello, World"); |
Rust provides an online playground to run rust code. If you don’t want to setup Rust on your local system. You can test or write your code here
https://play.rust-lang.org/
Here, I am going to show basic Hello World code in Rust. This is very simple!
1 2 3 4 5 6 | fn main() { let greet = "world"; println!("Hello {}!", greet); } |
Output:
Complex Example:
Here I am going to show some arithmetic calculation. Let’s find out the average in Rust. You always needed the main function otherwise it will generate an error. Call your another function from the main.
1 2 3 4 5 6 7 8 9 | fn avg(numbers: &[i32]) -> f32 { numbers.iter().sum::<i32>() as f32 / numbers.len() as f32 } fn main() { let numbers = [1, 3, 5, 10, 33]; println!("AVERAGE: {}", avg(&numbers)); } |
OutPut:
Primitive Types in Rust
Let’s see some primitives available in Rust and how to use them
1.bool
bool data types return the true or false value.
1 2 3 4 5 6 | fn main() { let bool_val: bool = true; println!("Bool value is {}", bool_val); } |
2.char
char datatype is used for characters or nonnumeric values.
1 2 3 4 5 6 | fn main() { let x_char: char = 'a'; println!("x char is {}", x_char); } |
3.i8/i16/i32/i64/isize
1 2 3 4 5 6 7 8 9 10 | fn main() { let num = 10; println!("Num is {}", num); let age: i32 = 40; println!("Age is {}", age); println!("Max i32 {}", <i32>::max_value()); println!("Max i32 {}", <i32>::min_value()); } |
4. Array
1 2 3 4 5 6 7 8 9 | fn main() { let rand_array = [1, 2, 3]; // Defining an array println!("random array {:?}", rand_array); println!("random array 1st element {}", rand_array[0]); // indexing starts with 0 println!("random array length {}", rand_array.len()); println!("random array {:?}", &rand_array[1..3]); // last two elements } |
Complex Data Structure Example:
I am going to explain how to implement class and struct in Rust programming language. Here is the Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | struct Circle { radius: f64, } impl Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } } fn main() { let c = Circle { radius: 2.0 }; println!("Area {}", c.area()); } |
Traits in Rust
A trait in Rust is a programming language feature that tells the Rust compiler about functionality a type must provide. Recall the impl keyword, used to call a function with method syntax:
- Interfaces
- Operator overloading
- Indicators of behaviour
- Bounds for generic
- Dynamic dispatch
Example of Traits:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | struct Circle { radius: f64, } impl Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } } // create a functionality for the datatypes trait HasArea { fn area(&self) -> f64; } // implement area for circle impl HasArea for Circle { fn area(&self) -> f64 { std::f64::consts::PI * (self.radius * self.radius) } } fn main() { let c = Circle { radius: 2.0 }; println!("Area {}", c.area()); } |
OwnerShip and Borrowing in Rust
Every value in Rust has an ownership scope and returning value has the transferring ownership to a new scope. Before we deep dive into ownership, let’s check out how other programming deal with memory management. Programming language uses stack or heap memory for storing data. The stack is faster than heap because CPU never has to search a place to put new data and the place to get the data from because that place is always on top of the stack.
In Rust, all of the literals like boolean, integers and strings are stored on the stack and for more complicated data, rust has heap memory. Heap is just a pile of memory. Heap is a little bit slower than the stack.
Ownership is a concept where each variable has a value and variable itself is called the owner. Each data has only one owner at a time and when the owner goes out of the scope, the value will be automatically dropped.
Here is some example code which explains scope in Rust
1 2 3 4 5 6 7 8 | fn main() { let a = 1; { let b = 2; // scope is different from main } } |
Once you create a bracket and define a variable in the bracket, variable scope is limited to this bracket only so you can define multiple brackets to define multiple scopes.
This is not exactly your code in Rust but the basic way to show you ownership.
Let’s look at another Example:
1 2 3 4 5 6 7 | fn main(){ let v = 1; let x = v; println!("{:?}",v); // ERROR : use of moved value: “v” } |
Here, I have defined variable v which actually owns an integer value. Now, I want to bind v to x so x = v. Now, I am trying to print out v.
Here, you will get an error that because v is moved to x. Here, I am moving the reference from v to x and after that actual reference of v disappears entirely from the scope. Only one reference can own a data at a time so that’s what exactly happening here.
To fix this, you have to use the borrowing. To assign the reference to v, to borrow v for a moment for x.
Types of Borrowing
There is two type of borrowing in Rust:
- Shared Borrowing (&T)
- Mutable Borrow (&mut T)
I have explained shared borrowing in this article. I am going to end this article here. You just try out Rust programming language by yourself and come to me if you find any difficulties in that.