Rust Programming Language: Core Concept You Should Know By Now.

Written by rockyessel | Published 2023/05/17
Tech Story Tags: rust | rustlang | rust-programming-language | learn-rust | basic-rust-knowledge | concept-rust | what-is-rust | rust-developers

TLDRRust is a programming language developed by Mozilla. The first release of Rust was on May 15th, 2015. The following is a list of the basic things someone starting to learn Rust should know. In Rust, Positional Arguments specify the position of a value in a string. Showing or printing a statement to the terminal in Rust is done using *[macros]via the TL;DR App

I'm writing this while learning Rust, so everything I write here is the basic things someone starting to learn Rust should know. So let's start with some history.

Rust History

Graydon Hoare, a Research employee at Mozilla started Rust as a personal project in the year 2006. Then later, Mozilla began sponsoring the project in 2009 as a part of the ongoing development of an experimental browser engine called Servo, which was announced in 2010.

The first release was on May 15th, 2015.

List of Basic Rust Knowledge

  • The main function is the beginning of every Rust program.
fn main(){
//Dont do this
let x = 5;
println!(x);
//This will throw an error.

//Do this instead.
 println!("{}", 1); 
 // or
 println!("{}", x);
 
 //Output is 1 or 5 for the variables x.
}
  • These {} are called placeholders in Rust.

  • In Rust, Positional Arguments specify the position of a value in a string. In positional arguments, each value is assigned a number based on the order of occurrence. So in the example, the first value is assigned 0, and the next is 1, so in a case where we value a third value, we will put 3 inside the placeholder if we want to display that data. Note that this is not a Named Argument.
fn main(){
  println!("Becoming the in the {0} is very important. So be {1}.", "industry", "patient");

  //output
  // Becoming the in the industry is very important. So be patient.  
}
  • Named Arguments take a name that stores a value. It is like declaring a variable to accumulate a value (string or numbers). So it works by specifying a name within the placeholder and assigning that name to a value to be inserted inside the string in the placeholder then displaying the output.
fn main(){
  println!("{blog_name} provides {type} needed.", blog_name="devBox", type="informations");
  
  //output
  //devBox provides informations needed.
}
  • Placeholders in Rust have different ways to print out data for the console or users. The placeholder used for converting values to binary, hexadecimal, and octal is called Placeholder Traits and is in these formats "Binary {:b}, Hexadecimal {:x}, Octal {:o}. Then we have a placeholder format for debugging, which is called Debug Trait. And with it, it is possible to display multiple values to the console using a placeholder with a colon followed by a question mark {:?}.

  • Showing or printing a statement to the terminal in Rust is done using macros, print! (), which prints strings to the console. println!(), prints strings to the console but appends a new line character at the end of the string. eprint!(), prints any string inside the parentheses as an error. And the last one, eprintln!(), prints string as errors but also appends a new line character at the end.
fn main(){
  //---print!()---
  //The following example prints “Rust Programming is fun, right?John is coding in Rust, cool right?” in one line.
  
    print!("Rust Programming is fun, right?");
    print!("John is coding in Rust, cool right?");
    
  //output Rust Programming is fun, right?John is coding in Rust, cool right? -- same line
  
  
  // ---println!()---
  //The following example prints “Rust Programming is fun, right?” on one line and “"John is coding in Rust, cool right?” on the new line.
  
    println!("Rust Programming is fun, right?");
    println!("John is coding in Rust, cool right?");
    
    /*
    output:
    Rust Programming is fun, right? --line
    John is coding in Rust, cool right? --another line
    */
    
  //---eprint!()---
  //The following example prints “Rust Programming is fun, right?” and “John is coding in Rust, cool right?” on the same line but as an error.
    eprint!("Rust Programming is fun, right?");
    eprint!("John is coding in Rust, cool right?");
    
     //output Rust Programming is fun, right?John is coding in Rust, cool right? -- same line
     
  // ---eprintln!()---
  //The following example prints “Rust Programming is fun, right?” as an error and appends a new line to it. Then prints “John is coding in Rust, cool right?” and appends a new line.
  
    println!("Rust Programming is fun, right?");
    println!("John is coding in Rust, cool right?");
    
    /*
    output as errors:
    Rust Programming is fun, right? --line
    John is coding in Rust, cool right? --another line
    */
    
}
  • Comments are readable instructions that help explain codes. But note that the compiler ignores them. Rust has three types of comment; two are commonly used. These comments are the Line Comments //, Block Comments /**/ and Doc Comments. Now the Doc Comments has a sub-type called Outer Doc Comments /// and Inner Doc Comments //!
 /// Outer Doc Comment

fn main() {
    // Line Comments
    //Example:
    //let mut x = 5;
    
    /*
    Block Comment
    Example:
    You can use the block comment when you want to disable a lengthy blocks of code
    let mut x = 5;
    */
    
   //! Inner Doc Comments
}
  • The Character in Rust, known as char, is used to store a single alphabetemojis, or Korean characters. And The value assigned to a char variable is enclosed in a single quote''. But note that, unlike some other languages, a character in Rust takes up 4 bytes rather than a single byte. It does so because it can store a lot more than just an ASCII value like emojisKoreanChinese, and Japanese characters.
fn main(){
  let char_letter = 'a';
  println!("{}", char_letter)

  // output: a
}

Concept to Know

Variables and Mutability:

  • In Rust, variables are immutable by default, meaning their values cannot be changed once assigned. To create a mutable variable, you need to use the mut keyword.
fn main() {
    let x = 5;  // Immutable variable
    let mut y = 10;  // Mutable variable
    y = 15;  // Updating the value of a mutable variable
    println!("x: {}, y: {}", x, y);
    // output: x: 5, y: 15
}

Data Types:

  • Rust is a statically-typed language, meaning you need to declare the type of each variable. Rust provides various built-in data types, including integers, floating-point numbers, booleans, characters, and more.
fn main() {
    let number: i32 = 42;  // Signed 32-bit integer
    let pi: f64 = 3.14;  // 64-bit floating-point number
    let is_true: bool = true;  // Boolean
    let letter: char = 'A';  // Character
    println!("Number: {}, Pi: {}, Is True: {}, Letter: {}", number, pi, is_true, letter);
    // output: Number: 42, Pi: 3.14, Is True: true
}

Control Flow:

  • Rust offers control flow structures like if-else, loops, and match expressions.
fn main() {
    let number = 7;
    // if/ if else/ else
    if number < 5 {
        println!("Number is less than 5");
    } else if number == 5 {
        println!("Number is equal to 5");
    } else {
        println!("Number is greater than 5");
    }
    
    // Loop
    let mut counter = 0;
    loop {
        println!("Counter: {}", counter);
        counter += 1;
        if counter >= 5 {
            break;
        }
    }
    
    //
    // match @desc this is Unqiue to Rust.
    let day = 3;
    match day {
        1 => println!("Monday"),
        2 => println!("Tuesday"),
        3 => println!("Wednesday"),
        _ => println!("Other day"),
    }
}

Match:

  • The match expression in Rust is a powerful construct that allows you to compare the value of an expression against a series of patterns and execute different codes based on the pattern that matches. It's similar to a switch statement in other programming languages but provides more flexibility and exhaustive pattern matching.
fn main() {
    let number = 5;
    
    match number {
        1 => println!("Number is 1"),
        2 | 3 | 4 => println!("Number is 2, 3, or 4"),
        5..=10 => println!("Number is between 5 and 10 (inclusive)"),
        _ => println!("Number doesn't match any pattern"),
    }
}

Functions:

  • Functions in Rust are defined using the fn keyword. You can specify the function's parameters and return type.
fn add_numbers(a: i32, b: i32) -> i32 {
    return a + b;
}

fn main() {
    let result = add_numbers(3, 4);
    println!("Result: {}", result);
    // output: Result: 7
}

Ownership and Borrowing:

  • Rust's ownership system ensures memory safety without the need for a garbage collector. It prevents issues like data races and dangling pointers. Rust follows the ownership, borrowing, and lifetimes concepts to manage memory.
fn main() {
    let s1 = String::from("hello");  // s1 owns the string "hello"
    let s2 = s1;  // s2 takes ownership of the string, s1 is invalidated
    println!("{}", s2);  // s2 can be used

    // output: hello  
    
    let s3 = String::from("world");
    let s4 = &s3;  // s4 borrows a reference to s3 and s3 is not invalidated
    println!("{}", s4);  // s4 can be used, but s3 is still valid
    // output: world
   
}

Conclusion

These are just a few basic concepts in Rust to get you started. Rust is a rich language with many more features and concepts to explore. Happy learning!


Written by rockyessel | I'm a MERN stack developer, and currently learning Solidity and Rust programming and I like writing and music.
Published by HackerNoon on 2023/05/17