Everything You Need to Know to Start Writing Rust

9 Min Read

Since its release in 2015, Rust has gained popularity as one of the favorite programming languages ​​of developers. Rust offers excellent performance and security features with an intuitive and concise syntax that makes the language desirable.

Rust is suitable for building various programs, including web apps, command-line tools, and network services. Rust includes many of the features you’d expect from a modern programming language, like concurrency, type inference, and more.


Getting Started With Rust

Rust is a cross-platform programming language that runs on most operating systems. To get started with Rust, head to the official Rust website and install the preferred version for your operating system.

Once you’ve installed Rust, you can start writing programs in Rust files with a rs extension. Rust is versatile and easy to learn. You’ll find it straightforward if you have prior programming experience.

Variables and Constants in Rust

Rust is highly expressive, and there are multiple ways to declare variables. You can use the let keyword to declare variables.

Here’s how you can declare variables in Rust:

 let a: String;
let b: i32;
let c: () = ();

the a and b variables are a string and an integer, respectively. the c variable is a Rust unit type that acts as a placeholder for functions and expressions.

After the optional data type declaration, you can declare and initialize variables with values ​​using an equal sign.

 fn main()
    let age: String = String::from("five years old");

    let age = 5;
    println!("", age);

The program declares two age variables before printing with the println! macros. The first age variable specifies the data type, and the second doesn’t.

You don’t have to specify the data type of a variable when you declare it. The Rust compiler infers the type from the value’s data type at compile time.

result from printing a variable

You can also declare constants in Rust with the const keyword in a similar fashion as declaring variables:

 const age: &str = "five years old";

You cannot modify the value of a variable you declare as a constant.

Rust provides functionality for single-line and block comments. You can use double forward slashes (//) for single-line comments:

 fn main() 
    let x = 5;

For multi-line comments (block comments), use a forward slash followed by an asterisk (/*) and close the block with an asterisk followed by a forward slash (*/):

 fn main() 
    This is a block comment that spans multiple lines.
    It is often used to describe a larger block of code.
    let x = 5;

Your comments should be concise and straightforward.

Arrays in Rust

Arrays are a fixed-size collection of elements of the same data type. Rust allocates arrays on the stack by default.

Here’s how you can declare arrays in Rust:

 fn main() 
    let numbers = [1, 2, 3, 4, 5];

the numbers array contains five items. You can access the value at a location in an array using its index:

 fn main() 
    let numbers = [1, 2, 3, 4, 5];
    let x = numbers[3];
    println!("", x)

the play function prints the x variable that accesses the fourth element of the array.

result from printing the array

Vectors in Rust

Rust provides vectors to cover up the limitations of the array. Vectors are dynamically sized; they can grow and shrink as needed.

Here’s how you can declare vectors in Rust:

 fn main() 
    let my_vec: Vec<i32> = vec![1, 2, 3, 4, 5];
    let x = my_vec[3];
    println!("", x)

the my_vec vector is a vector of 32-bit integers. the x variable accesses the vector’s fourth element, and the play function prints the value to the console.

Rust’s Conditional Statements

Conditional statements are one of Rust’s control structures for decision-making in programs. You can use the if and else keywords to handle decisions in your programs.

Here’s an if statement that prints a string to the console based on the equality of two integers.

 fn main() 
    let a: i32 = 12;

    if a == 12
        println!("a equals twelve");

the play function prints the string with the println! macro since the variable equals 12.

You can use the else keyword to handle cases where the if statement evaluates false:

 fn main() 
    let a: i32 = 12;

    if a == 123
        println!("a equals twelve");
        println!("a does not equal twelve");

In this example, the else statement runs because a’s value is not equal to 123.

You can declare match statements with the matches keywords for complex conditionals:

 fn main() 
    let age: i32 = 7;

    match age
        1 => println!("one"),
        2 => println!("two"),
        3 => println!("three"),
        _ => println!("zero"),

the play function matches the age variable to cases in the matches statement and executes the expression that matches the value. The underscore (_) is the default statement that runs if there’s a match for the value.

Loops in Rust

Rust provides loops for repetitive tasks. Rust has three main types of loops: loops, whileand for loops.

the loops keyword creates an infinite loop that runs until it encounters a break keyword:

 fn main() 
        println!("printed repeatedly until break statement is encountered.");

the while loop is handy when you want to repeat a block of code as long as a condition evaluates to true:

 fn main() 
    let mut count = 0;

    while count < 5
        println!("The count is ", count);
        count += 1;

A for loop is good for iterating over a collection of items, like an array:

 fn main() 
    let numbers = [1, 2, 3, 4, 5];

    for item in numbers.iter()
        println!("The current item is ", item);

this for loop iterates through the numbers array and prints each item to the console.

Declaring and Calling Rust Functions

use the fn keyword to declare a Rust function, followed by the function name, a list of parameters, and a return type (if any).

Here’s how you can declare a function with parameters and a return type:

 fn add(a: i32, b: i32) -> i32 
    return a + b;

the add function takes in two 32-bit integers and returns a 32-bit integer, the sum of the two parameters.

To call a function from elsewhere in your code, simply specify the name and arguments (if any):

 fn main() 
    let result = add(2, 3);
    println!("2 + 3 = ", result);

the result variable holds the result from calling the add function. the play function prints the result to the console using the println! macros.

Structures in Rust

Rust provides structs for defining custom data types that group related values. Structs are blueprints for creating objects with specific properties.

Here’s how you can declare a struct:

 struct Person 
    name: String,
    age: u32,
    is_male: bool,

the Person struct has three fields: a String, an unsigned 32-bit integer, and a boolean.

After defining a struct, you can create instances of it in other parts of your program:

 fn main() 
    let person1 = Person
        name: String::from("Candace Flynn"),
        age: 16,
        is_male: false,

the person1 variable is an instance of the Person struct. On instantiation, you can assign values ​​to the struct fields. You can create as many instances of a struct as you please.

You Can Implement OOP Concepts in Rust

Rust is flexible, and you can implement the OOP concepts in Rust with built-in data structures like structs.

You’ll use structs as an alternative to classes. With Rust’s struct, you can define a blueprint for the type and implement the different OOP concepts with the functionalities Rust provides on structs.

Share this Article