logo
CommunityResearch Program

Resources

BlogForum
Back to blog
A Comprehensive guide to Rust Programming Language for Smart Contracts Development | Web3

November 22, 2023

A Comprehensive guide to Rust Programming Language for Smart Contracts Development | Web3
bymetaschoolinCommunity

The blog is submitted to Developer Nation by Metaschool. Join Metaschool to start your Web3 Journey today!

Before we dive into the world of Rust, Consider Joining our Emerging Technologies Developer Survey and have a chance to win amazing prizes like Ledger Nano S Plus & case, 2x Raspberry Pi 5, 5x YubiKeys Hardware 2fa keys and more.

The survey aims to get insights and perspectives from developers to understand better-decentralised tech and emerging technologies and their impact on the development industry.

Take the survey now!

Introduction to Rust

The Rust programming language is fast, memory-efficient and statically typed. As with most other languages, Rust was launched to address and bridge some significant gaps within coding and development. For instance, it is common for developers to face memory errors in languages like C++, which can multiply into problems like miscalculations, missing allocations, malfunctions, unresponsiveness, and spontaneous restarts, to name a few. Rust specifically addresses the issues of memory errors and concurrent programming.

Moreover, it is an ahead-of-time compiled language. This means that if User A compiles a code and gives the executable to User B, User B does not necessarily need to have Rust installed to run the program.

Rustaceans unite for safety.
Rustaceans unite for safety. Source: Github

Today, Rust is considered to be a good alternative to old and big-shot languages like C++ and Java in different capacities. Many web2 and web3 developers are opting for it as their primary language for coding. In fact, many have switched to Rust despite having languages like Java as their first programming language.

Origins of the Rust programming language

Designed by Graydon Hoare, the conceptualization of the Rust programming language started in 2006. Not many know but Rust was named after the rust fungi which happen to be a specialized plant pathogens with several unique features. 

Hoare was working at Mozilla Foundation while he was developing this fungi-inspired programming language. He worked on it for quite some time and in 2010, Rust officially became a Mozilla project. Five years later, in 2015, Rust 1.0 got launched, and Mozilla became its legal and financial sponsor.

In 2021, the formation of Rust Foundation was announced, and soon after Rust management shifted to the foundation and the rest is history.

What is Rust used for?

Rust was first majorly used for performance enhancement, security strengthening, and memory management. Later on, it started being used to write smart contracts, build decentralized applications, and mint tokens.

Developers also use Rust so that they can ensure memory safety and thread safety and eliminate as many bugs as they can while compilation. And Rust’s rich “type” system also

comes in handy. The programming language is said to have a diverse, and enhanced type system that allows users or developers to flexibly describe their types and determine how the objects associated with these types can interact.

What makes Rust well-suited for blockchain development?

Rust has definitely gained quite some traction in recent times. It has grown popular, especially in the blockchain industry. The primary aim or goal of any programming language is to serve its programmers to the core and Rust knows this very well.

rust programming language
Source: Metaschool

1. Easy to learn and write code

Rust is comparatively simpler and less complex to write code on. This is not really the case with some popular languages that are used in blockchain development. For example, messing around with threads on languages like C++ while writing code can be quite difficult. And if you go installing dependencies on C++, be ready for nightmares. Rust addresses these problems within the language itself.

From its vast libraries and multi-purpose frameworks to its super useful tools, Rust provides a unified ecosystem where you can go and get all the information you need about the language. This is essentially due to Rust being properly and carefully documented. Thus, coding is made ridiculously easy on Rust. No doubt it remains the most admired language.

2. Has a robust memory management system

The second reason which makes Rust a well-suited language for blockchain development is its memory management. Memory management happens to be a key challenge in developing complex systems like that of blockchain. Rust provides safety to blockchain memory without garbage collection.
Garbage collection (GC) is a memory recovery feature that is built into programming languages such as C++ and Java. While it is a feature not without benefits, it has some drawbacks, too. For example, in languages like Java, GC can lead to runtime overhead, resulting in problems for large-scale projects such as coding a blockchain. Thus, Rust does not support garbage collection.

3. It’s also quite fast

While C++ and Rust are strong competitors C++ tends to be a tad bit faster than Rust. However, Rust’s memory management system comes in handy here. It makes the execution of codes an extremely easy and stress-free process. Rust came a little late so it really observed the challenges faced by developers while coding in languages like C++.

Additionally, Rust has a large number of add-ons that adds to the overall speed of the language. Be it the serialization of structures or asynchronous programming, Rust has got libraries, tools, and frameworks to do the needful.

Blockchain projects built with Rust

When it comes to projects using Rust, there are several in the web3 space. Let’s take a quick look.

1. Solana

Solana, a proof-of-stake (PoS) blockchain, has been using Rust to write smart contracts. It’s a strong competitor to Ethereum and home to diverse blockchain-based web3 applications. From Solana dApps to Solana smart contracts to Solana NFTs, Rust has been efficiently leveraged to code these diverse web3 applications on the Solana blockchain.

🔍 Explore: Who is Anatoly Yakovenko? Founder of Solana Blockchain

2. Near Protocol

Rust is used to build tools for developing and interacting with Near Protocol. These tools include wallets, compilers, and explorers. Additionally, Rust is used to create and write dApps and smart contracts as well, respectively.

3. Polkadot

Polkadot, a famous blockchain, is built upon a blockchain framework called Substrate. The Substrate framework is coded with the Rust programming language and allows to create blockchains like Polkadot. This shows that Polkadot would probably not exist without Rust. Rust also helps the blockchain in implementing its core runtime which is responsible for executing smart contracts. Polkadot’s interoperability vision consists of parachains that run parallel to its blockchain. Rust is greatly used when it comes to the development of parachains.

4. Acala Network

Acala is a blockchain network that uses the Rust programming language in many different ways. Some of the constituents of Acala’s infrastructure were designed and coded with Rust. These include the consensus engine, wallet, and run-time. Rust is a recommended language for the development of parachains and used to write smart contracts on the network.

5. Comit

A cross-blockchain network that facilitates trustless cross-blockchain applications like Bitcoin, Solana, etc. While cross-blockchain communication is not a new thing, Comit leverages the Rust programming language to do the needful. Comit has a GitHub repository with a bunch of projects, all built using Rust.

6. Exonum

An open-source, enterprise-grade blockchain framework that helps businesses, governments, and professional organizations securely bring blockchain projects to life. Exonum majorly employs Rust for its projects. From the look of it, Exonum seems to be quite inspired by Hyperledger Fabric. It also has a well-curated blockchain repository on GitHub.

7. Bonfida

Another open-source project that we have is Bonfida. It is a free token vesting program that is made completely on Rust. It is also built for the Solana blockchain. Bonfida helps you in determining, say, how many tokens are to be released at one time. It makes a decent vesting tool powered by Rust. Bonfida also has a list of projects and programs on Github that you can check out.

8. Fe

Did you know that there is a replacement for Solidity called Fe? You can use this language to write smart contracts on Ethereum. What is mind-boggling is that Fe is created on Rust and it serves as an alternative to Solidity. That’s too many languages. It also offers precise gas estimations along with other cool features. Do you think you would want to use Fe to develop smart contracts and dApps? You can also check out their GitHub.

9. Astar

Lastly, there is Astar, which is the future of smart contracts for multichain blockchains. What this means is that you can write smart contracts and by using Astar, you can deploy it to multiple blockchains. Astar proudly calls itself the dApp hub for future blockchains. Astar also has a GitHub repository that you can check out.

Common programming concepts in Rust

Get your pens out, it’s time to take notes!

rust
Source: Evan Miller

1. Variables and mutability

Variables on Rust are completely immutable. There have been cases when data have been tried to be changed or modified. However, Rust ensures that you can rest assured about your variables remaining immutable. If you are a beginner and you are not too sure about variables, you have the option to turn your immutable variables into mutable ones.

2. Data types

Each value that you see on Rust belongs to a certain data type. This helps Rust to determine which value is specified to which data type. There are two major data types that have sub-types and they are as follows:

a. Scalar

The scalar data type represents all the singular values within Rust. There are four primary sub-type of the scalar data type and they are as follows:

integer: a number with no fractions. For example, 5 is an integer but 5.5 is not an integer.

floating-point: opposite of integers, floating-point numbers are numbers that have a fractional component to them and these are the numbers with decimal points. For example, 5.5 is a floating-point number but 5 is not.

booleans: the boolean type has only two values. It can either be true or false. In Rust, this type of data is specified as a bool.numeric: numeric operations include the basic DMAS rules which include the addition, subtraction, division, and multiplication of numbers.

b. Characters

The char type is the most primitive alphabetic type.

c. Compound/collections

Compound data types, as the name goes, group multiple values into one type. There are two primitive compound types – tuple and array.

tuple: a tuple is a general way of grouping together several values with various types, into one compound type. Tuple happens to have a fixed length. Once you have declared a tuple size, it can’t grow or shrink further. Tuple is created by writing a comma-separated list of values inside parentheses.

array: another way to achieve a compound type with respect to your data is through an array. In an array, you have a homogenous group of data types, unlike a tuple in which you have a heterogeneous group of data types.

3. Functions

Functions in Rust are yet another concept. They are used to encapsulate a block of code that happens to perform a specific task. They can have input parameters and return values. Rust functions have a clear signature, including the return type, and can be called from other parts of the code. They play a fundamental role in structuring and organizing Rust programs.

4. Comments

This is an interesting concept in Rust. Comments in Rust allow you to add explanatory or descriptive text to your code that is ignored by the compiler. Rust supports two types of comments: single-line comments, which are distinguished by / /, and multi-line comments, enclosed between /* and */. Comments are useful for documenting your code, providing context, and making it more understandable to other developers or to yourself when revisiting the code in the future.

5. Control flow and loops

Rust coding is the executing of statements and expressions. Control flow in Rust determines the order in which these statements and expressions are executed. These expressions and statements are specified by if and else statements or match expressions.

a. Conditions

In Rust, conditions are typically expressed using if and else statements or match expressions. They allow you to make decisions and execute different blocks of code based on whether a condition evaluates to true or false.

b. Loops

The loop keyword tells Rust to execute a block of code over and over again until you stop it. Thus, unbound looping is a feature of Rust, unlike Clarity. Moreover, if you have commanded a certain condition, looping will continue until that condition is met.


🔮 Explore more: Full Guide to Clarity | Smart Contract Programming Language

6. Ownership and borrowing

Ownership in Rust enables it to make memory safety guarantees without the need for a garbage collector or GC. GCs are often used in languages like Java but Rust does not entertain such a feature. Ownership basically is a set of rules that govern how a program manages memory.

As far as borrowing is concerned, it is a mechanism that allows multiple references to access and uses a value without transferring ownership. It enables safe and efficient resource sharing. Borrowing is governed by strict ownership and borrowing rules enforced by the Rust compiler to prevent common issues like data races and dangling references.

7. Structs

Structs, short for structures, are user-defined data types that allow you to group related data together. They share similarities to classes in object-oriented programming and provide a way to define custom data structures.

8. enums

Enums, short for enumerations, are data types that allow you to define a type by enumerating its possible values. Enums are useful when you have a fixed set of values that a variable can take. Values in enums are called variants. They can either be associated with a data type or be empty.

9. Methods

Methods in Rust are functions that are defined within the context of a struct, an enum, or a trait implementation. They’re associated with a particular type and can access the data of that type. Moreover, they can also help you define behavior specific to the type.

10. Error handling

In Rust, error handling is achieved using the Result type and the panic! macro. The Result type represents the result of an operation that can either be successful (Ok) or contain an error (Err). It allows you to handle and propagate errors in a structured manner.

11. Tests

In Rust, Tests allow you to write tests for your code to ensure the code behaves as it is expected to. There is a specific attribute that is written as #[test] and they are capable of asserting certain conditions which they do using the assert! attribute.

Rust tools, libraries, and frameworks for development

1. Tools

The Rust programming language uses some industry-grade tools which help developers tremendously and they greatly add to one’s overall efficiency. These tools are as follows:

a. Rustfmt

This particular code is handy as it automatically formats your code on Rust, making it easier to read, write and maintain. In fact, the Rustfmt tool also reformats your code into community code style. For context, a community code style is a set of conventions and guidelines followed by the Rust community when writing code.

rustfmt
Source: rust-lang/Github

b. Clippy

Clippy is an interesting and useful Rust tool that developers can use. It helps catch common mistakes within a Rust code. There are three distinct ways to use Clippy in your code.

Simply add Clippy to the entirety of your code. There is always a .bazelrc file which is actually your workspace file. You can simply add the following to your file and it will apply to the code as a whole, as in to all Rust targets:

build –aspects=@rules_rust//rust:defs.bzl%rust_clippy_aspect

build –output_groups=+clippy_checks

Execute the Clippy checker on a specific target by using the rust clippy(name, deps) command where name indicates a unique name for the target and deps signifies target/s to run Clippy on.Finally, one can execute the Clippy checker on specified targets by using this command rust_clippy_aspect(name)

c. Cargo Doc

Cargo is a whole package manager for Rust. It is essentially a build tool with multiple commands. Cargo is majorly focused on dependency resolution and ensuring a reputable build. One of its commands is Cargo Doc. Cargo Doc helps build a package’s documentation. Documentation in coding is of immense importance because if you can’t read it, you can’t write it. The output of Cargo Doc is in rustdoc’s usual format.

2. Libraries

Coding libraries happen to increase a developer’s overall efficiency. Libraries usually have pre-written, reusable, tried and tested chunks of code that reduce your work and help you simultaneously. Here are the top 3 Rust libraries:

a. Hyper

Handling and making HTTP requests in Rust is a common phenomenon and an action that is performed more than once. This also includes parsing the results. Hyper, as a library, makes handling HTTP requests an easy process for developers.

b. Tokio

Tokio is an event-driven, non-blocking I/O library for writing asynchronous applications. It has different features such as a task scheduler, asynchronous sockets, etc.

tokio
Source: tokio.rs blog

c. Iced

Iced is a valuable cross-platform GUI library used by developers who code in Rust. It is mainly focused on simplicity and type safety. Additionally, it has features like a responsive layout, built-in widgets like scrollables, text inputs, etc.

3. Frameworks

In coding frameworks are crucial. They provide assistance in the development process. Here are some of Rust’s popular frameworks.

a. Serde

A lightweight and general purpose that deals with serialization and deserialization of Rust data structs in an efficient fashion.

b. Actix

Actix is a more specific framework. It is a high-performance, actor-based web framework that isolates requests and improves the scalability and performance of web applications.

c. Rocket

As mentioned at the beginning of this guide, Rust has a rich type system. Rocket, as a framework, utilizes Rust’s type system to provide a simple and secure development experience. It also has a set of macros (a code that generates a code) and abstractions to simplify web development.

How to write a basic smart contract in Rust

  1. Create a new Rust project.

2. Add the ink_lang crate to your project.

3. Create a counter.rs file in your project.

4. Write the following code in the counter.rs file:


use ink_lang as ink;
#[ink::contract]
mod counter {
    #[ink(storage)]
    pub struct Counter {
        count: u32,
    }
    impl Counter {
        #[ink(constructor)]
        pub fn new() -> Self {
            Self { count: 0 }
        }
        #[ink(message)]
        pub fn increment(&mut self) {
            self .count += 1;
        }
    }
}

5. Compile your project using the cargo build command.

6. Deploy your contract to a blockchain network.

The future of Rust as a programming language

In core software, Rust is used pretty much everywhere. Be it operating systems, drivers, and server infrastructure, Rust always has an answer and a way. Gradually, it has made its place in the blockchain space as well.

Several agree it is an upward trajectory for Rust from here because of its speed (which is almost as much as that of C++) and increased safety. To add, before Rust, languages like Java, C++, etc. were some of the fastest languages. Rust’s key selling point became its safety along with speed.

Due to this and more reasons an industry shift is being seen in which developers will start adapting to Rust. Thus, the future of Rust as a programming language looks bright for now. Only time will tell if that is going to stand true.

FAQs

What kind of language is Rust?

Rust is a, high-level, statically-typed programming language.

What are the top 5 blockchains that use Rust?

The top 5 blockchains that use Rust are

1. Polkadot

2. Elrond

3. Solana

4. Near Protocol

5. Hyperledger Sawtooth

Is Rust better than C++?

There is no one answer to this question. Rust and C++ are both great languages in their own capacity. If Rust has better framework support then C++ has a more rich library. So, it depends on what you are looking for. And if a language fulfills that, it is definitely a better language.

Which is faster, Python or Rust?

Rust is more memory efficient which makes it faster than Python.

Are Rust developers in demand?

Since Rust has been gaining popularity in the blockchain space, Rust developers have been in great demand.

What is the salary for Rust developers in 2023?

The average salary of a Rust developer in 2023 is 127k USD per annum. The base salary is between $60k USD (minimum) and $250k USD (maximum).

Web3

Recent Posts

June 07, 2024

SOA vs. Microservices: Which is the Right Choice For Your Firm?

See post

wwdc24

June 11, 2024

A Roundup of WWDC24. AI Takes Center Stage, But Developers Rejoice! Apple Unleashes a Dev Powerhouse.

See post

June 07, 2024

Vue.js vs. React: Which is the Ideal JavaScript Framework for 2024?

See post

Contact us

Swan Buildings (1st floor)20 Swan StreetManchester, M4 5JW+441612400603community@developernation.net
HomeCommunityResearch ProgramBlog

Resources

Knowledge HubPulse ReportReportsForumEventsPodcast
Code of Conduct
SlashData © Copyright 2024 |All rights reserved