Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Problems
  • C
  • C++
  • Java
  • Python
  • JavaScript
  • Data Science
  • Machine Learning
  • Courses
  • Linux
  • DevOps
  • SQL
  • Web Development
  • System Design
  • Aptitude
  • GfG Premium
Open In App
Next Article:
Introduction to Rust Programming Language
Next article icon

Introduction to Rust Programming Language

Last Updated : 14 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Rust is a blazing fast and memory-efficient static compiled language with a rich type system and ownership model. It can be used to power performance-critical services while guaranteeing memory-safety and thread-safety, empowering developers to debug at compile-time. In addition to that Rust has great documentation and a user-friendly compiler with top-end tools like integrated package managers and multi-editor with features like type inspection and auto-completion. Rust prevents all the crashes, and, interestingly, Rust is safe by default like JavaScript, Ruby, and Python. This is much more powerful than C/C++ because we cannot write the wrong parallel code you can never see fault in rust. It is very fast in representing a lot of programming paradigms very well. 

Introduction-to-Rust-Programming-Language

But the question arises as there are already so many programming languages like Python, C++, Java, etc, then why the need for developing a new programming language? The answer to this is the other programming languages have a lot of control over the hardware that you are running, like, you can optimize it well, translate directly to assembly code, but it's not very safe.

So rust provides us all the controls that we can have and all the levels of security that we can achieve.

Rust is using Rust which means that all the standard compiler libraries are written in rust; there is a bit of use of the C programming language but most of it is Rust. The big project of Rust is "servo",  It is a project to write out the totally parallel layout engine like Gecko in Firefox or WebKit in Safari.

Servo built the layout engine, something to render HTML from bottom to top.

Table of Content

  • Functions in Rust
  • Concept of Ownership
  • Concept of Borrowing
  • Memory management in Rust
  • Mutability
  • Structure in Rust
  • Tuple
  • Rust Type System
  • Advantages of Rust
  • Disadvantages of Rust

Functions in Rust

Functions are the block of reusable code that can perform similar related actions. You have already seen one of the most important functions in the language: the main function, which is the entry point of many programs. You’ve also seen the “fn” keyword, which allows you to declare new functions. Rust code uses snake case as the conventional style for function and variable names. In snake case, all letters are lowercase and underscore separate words.

Syntax:

fn functionname(arguments){
code
}

Here,

  1. To create a function we need to use the fn keyword.
  2. The function name is written after the fn keyword.
  3. Arguments are passed after function name inside parenthesis.
  4. You can write function code in function block.

Example: The below function simply prints "Hello, World!" in the console:

Rust
fn main() {    println!("Hello, world!"); } 

Output:

Hello, World!

Concept of Ownership

The concept of ownership is that when you own something you can decide to pass it to someone else, if you have a book, and you have done reading it you can permanently give it to someone and not worry about it. 

Below is the Rust program to implement the approach:

Rust
fn helper() -> Box<i32> {     let three = Box::new(3);     three // Ownership is transferred implicitly }  fn main() {     // Acquire ownership of the return value     let my_three = helper();     println!("{}",my_three); } 

Output:

3

Concept of Borrowing

Owned values in rust can be borrowed to allow usage for a certain period of time The "&" sign represents the borrowed reference. Borrowed values have a lifetime and are valid for that time only. Borrowing prevents moving. While there is an active borrow I can not transfer ownership. I still own it but cannot transfer it until I handed it in to really relinquish that borrowed. 

Below is the Rust program to implement the approach:

Rust
fn main() {   let a: &i32;   {     // b lifetime is not same as a     let b = 3;      a = &b;     println!("{}",b);   }        println!("{}",a); } 

Here "a" and "b" has a different lifetime, so it will not work.

Rust
fn main() {   let a: &i32;      // a and b have same lifetime   let b = 3;     a = &b;   println!("{}",a);   println!("{}",b); } 

Output:

3
3

Here "a" and "b" have the same life, so it will work. Borrow can be nested. Through cloning, borrowed values can become owned.

Memory management in Rust

  1. Rust has fine-grain memory management but is automatically managed once created.
  2. In Rust when you allocate memory you never have to really free it you can decide when to free it but never call it. Rust takes care of it automatically.
  3. Each variable has a scope it is valid for, and it gets automatically deallocated once it goes out of scope.
  4. In rust, each program is allocated memory from the operating system.
  5. Rust also has a shared memory where we can have a reference piece of data, we can use ownership to keep track of reference count.

Different memory

1. Heap:

  • It is the biggest memory block and is managed by the rust ownership model.
  • At this place, all the dynamic data is stored.

2. Stack:

  • All values in rust are allocated on the stack.
  • At this, the static memory is allocated by default.
  • There is one stack per thread.
  • It includes structures and pointers to dynamic data.

Mutability

Values in rust are immutable by default and must be tagged as being mutable(if needed).

Below is the Rust program to implement Mutability:

Rust
fn main() {   let x = 2;      // It will show an error   x = 9;       println!("{}", x); } 

The above example will show an error because we have not tagged it as mutable.

Rust
fn main() {   let mut x = 2;      // This will work fine   x = 9;       println!("{}", x); } 

Output:

9

This will work fine as we have tagged it as being mutable. As in this case we are explicitly mutating it.

Structure in Rust

The structure is a user-defined data type in rust that is used to combine different data items of a different type. Structure defines data as a key-value pair. The struct keyword is used to define Structures in Rust.

Syntax: 

struct Name_of_structure {
field1:data_type,
field2:data_type,
field3:data_type
}

Below is the Rust program to implement structure:

Rust
struct Employee {   name: String,   company: String,   employee_id: u32,   profile: String  } fn main() {   let value = Employee {     name: String::from("Geek"),     company: String::from("Geeksforgeeks.org"),     employee_id: 007,     profile:String::from("Manager"),    };   println!("Employee: {} of {} Company bearing EmployeeID {} is of {} level.",     value.name,      value.company,     value.employee_id,     value.profile); } 

Output:

Employee: Geek of Geeksforgeeks.org Company bearing EmployeeID 7 is of Manager level.

This is an example of how we create structures in rust. This will compile perfectly.

Tuple

A tuple in rust is a finite heterogeneous compound data type, meaning it can store more than one value at once. In tuples, there is no inbuilt method to add elements into a tuple. We can use the index to get the value of a tuple, and we also can not iterate over a tuple using for loop.

Syntax:

("geeksforgeeks", 1, 'geek')

Below is the Rust program to implement Tuple:

Rust
// Rust program to get value from tuple // using index fn main() {     let gfg = ("cp", "algo", "FAANG", "Data Structure");           // complete tuple     println!("complete tuple = {:?} ", gfg );           // first value     println!("at 0 index = {} ", gfg.0 );           // second value     println!("at 0 index = {} ", gfg.1 );           // third value     println!("at 0 index = {} ", gfg.2 );           // fourth value     println!("at 0 index = {} ", gfg.3 ); } 

Output:

complete tuple = ("cp", "algo", "FAANG", "Data Structure") 
at 0 index = cp
at 0 index = algo
at 0 index = FAANG
at 0 index = Data Structure

Rust Type System

In Rust, every variable, value, and item has a type. The type defines how much memory it is holding and which operation can be performed on the value. The below table states all the types in Rust:

Type

Contents

Primitive Types

Boolean, Numeric, Textual, Never

Sequence Types

Tuple, Array, Slice

User-defined Types

Struct, Enum, Union

Function Types

Functions, Closures

Pointer Types

References, Raw pointers, Function pointers

Trait Types

Trait objects, Impl trait

Advantages of Rust

  1. Quick debugging and testing: Rust is a very fast language and supports quick and effective debugging.
  2. Rust supports more complex code as compared to other languages, so we can achieve more in less code.
  3. It enables cross-platform development.
  4. Ease of integration: Rust can be easily integrated with C and many other famous programming languages.
  5. Rust is safer than other programming languages.
  6. There is a wide community of developer which support Rust.

Disadvantages of Rust

  1. Due to complexity, it may take a longer time to learn Rust.
  2. In rust, code can be less efficient and also it takes more time to compile.
  3. As it is more complex, so it may take more time to complete apps written in Rust.
  4. It is a new language, so it will take more time to spread over and jobs in rust also may not be as much as in other popular programming languages.
  5. In some cases, rust can leak memory and become slower than a popular programming language.
  6. Hard to maintain due to its large code base.

Next Article
Introduction to Rust Programming Language

A

akhilsharma870
Improve
Article Tags :
  • Rust
  • Rust-basics
  • Listicles

Similar Reads

    Rust: The Programming Language of the Future?
    In the ever-changing landscape of programming languages, Rust has positioned itself as a strong candidate to be crowned “Programming Language of the Future.” Developed by Mozilla in 2006 and currently maintained by the Rust Foundation, Rust has drawn significant attention and uptake due to its uniqu
    7 min read
    Rust - Generic Function
    In Rust, Generic functions are very useful. Generic make code more flexible and provide more functionality to the callers of the function. It prevents code duplication as it is not required to define different functions of different types. Generics are specified in the signature of function where we
    3 min read
    Top 7 Rust Game Engines in 2025
    Are you ready to dive into game development but unsure which engine to choose? Have you considered the power and safety of Rust for your next project? Rust has been gaining popularity for its performance and reliability, making it an excellent choice for game development. Whether you're building a 2
    8 min read
    Rust - Higher Order Functions
    In Rust, we have a concept of Higher order functions that passes the function to another function once the variable is stored in another function. To define a function in Rust, we use the fn keyword. Syntax: fn <function name>() { } Higher-order functions in Rust are those functions that take
    2 min read
    Rust - Hello World Program
    Every programmer starts their programming journey with a simple "Hello World!" program. In this article, we will write our first "Hello World!" Rust program. If you have not yet installed Rust on your system, please go through the link and install it. In this article we will be working on the follow
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences