DEV Community

Cover image for Rust 1 - Basic syntax
Petr Janik
Petr Janik

Posted on • Updated on

Rust 1 - Basic syntax

Installation

Getting started official guide

cargo new my-project # create new project
cargo build # build the project
cargo run # run main()
Enter fullscreen mode Exit fullscreen mode
rustup --version
rustup check # checks if newer version is available
rustup update
Enter fullscreen mode Exit fullscreen mode
cargo fmt # runs rustfmt formatter
cargo clippy # detects and fixes problems in code
Enter fullscreen mode Exit fullscreen mode

Hello World!

fn main() {
    println!("Hello, world!"); // '!' means this is a macro
                               // strings are enclosed in double quotes
}
Enter fullscreen mode Exit fullscreen mode

Binding

fn main() {
    let x = 5; // this is binding, in other languages know as definition
               // x is immutable (constant)
    println!("Value of x is: {}", x);

    // x += 5 would throw an error
    // x = 10 also throws an error

    let y: u32 = 6;
    println!("Value of y is: {}", y);
}
Enter fullscreen mode Exit fullscreen mode

Shadowing

fn main() {
    let x = 5;
    println!("Value of x is: {}", x);

    let x = x + 5;
    println!("Value of x is: {}", x);
}
Enter fullscreen mode Exit fullscreen mode

Mut binding

fn main() {
    let mut x = 5; // mutable binding, uses keyword 'mut'
    println!("Value of x is: {}", x);

    x = 10;
    println!("Value of x is: {}", x);


    x += 1; // Rust does not support neither x++ nor ++x
    println!("Value of x is: {}", x);
}
Enter fullscreen mode Exit fullscreen mode

Data types

Number of bits Signed Unsigned
8-bit i8 u8
16-bit i16 u16
32-bit i32 u32
64-bit i64 u64
128-bit i128 u128
arch isize usize

Numeric literals

Type Example
Decimal 98_222
Hexa 0xff
Octal 0o77
Binary 0b1111_0000
Byte (u8) b'A'

Constants

const MAX_POINTS: u32 = 100_000;
Enter fullscreen mode Exit fullscreen mode

Floating point numbers

fn main() {
    let x = 2.0; // f64
    println!("Value of x is: {}", x);

    let x: f32 = 10;
    println!("Value of x is: {}", x);
}
Enter fullscreen mode Exit fullscreen mode

Type conversion

fn main() {
    let x = 2;
    let y: f64 = x as f64;
    let z: i32 = y as i32;

    let pi: f32 = 3.14;

    let u: f32 = pi.trunc();
    let v: f32 = pi.ceil();
    let w: f32 = pi.floor();

    println!("Value of u is: {}", u); // 3
    println!("Value of v is: {}", v); // 4
    println!("Value of w is: {}", w); // 3
}
Enter fullscreen mode Exit fullscreen mode

Booleans

fn main() {
    let t = true;

    let f: bool = false; // explicit type

    let value: i32 = f as i32; // bool is in Rust always either 0 or 1. Nothing else.
}
Enter fullscreen mode Exit fullscreen mode

Characters

fn main() {
    let c = 'z'; // 'char'
    let z = 'ℤ'; // 'char'
    let heart_eyed_cat = '😻'; // 'char'; character is utf-8, 
                               // therefore it is not compatible with byte, i. e. u8
}
Enter fullscreen mode Exit fullscreen mode

Tuples

fn main() {
    let tup: (i32, f64, u8) = (500, 6.4, 1);

    let tup = (500, 6.4, 1);

    let (x, y, z) = tup;

    println!("The value of y is: {}", y);

    let five_hundred = tup.0;

    let six_point_four = tup.1;

    let one = tup.2;
}
Enter fullscreen mode Exit fullscreen mode

Arrays

fn main() {

    let a: [i32; 5] = [1, 2, 3, 4, 5];

    let b = [1, 2, 3, 4, 5];

    let first = a[0];
    let second = a[1];

    let index = 2;

    let element = a[index];

    println!("The value of element is: {}", element);

    let months = ["January", "February", "March", "April", "May", "June", 
                   "July", "August", "September", "October", "November", 
                  "December"];
}
Enter fullscreen mode Exit fullscreen mode

Functions

fn main() {
    another_function(5, 6);
}

fn another_function(x: i32, y: i32) {
    println!("The value of x is: {}", x);
    println!("The value of y is: {}", y);
}
Enter fullscreen mode Exit fullscreen mode

Conditions

fn main() {
    let number = 6;

    if number % 4 == 0 {
        println!("number is divisible by 4");
    } else if number % 3 == 0 {
        println!("number is divisible by 3");
    } else if number % 2 == 0 {
        println!("number is divisible by 2");
    } else {
        println!("number is not divisible by 4, 3, or 2");
    }

    let condition = true;
    let number2 = if condition { 5 } else { 6 };

    println!("The value of number is: {}", number2) // 5
}
Enter fullscreen mode Exit fullscreen mode

Loop

fn main() {
    let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };

    println!("The result is {}", result); // 20
}
Enter fullscreen mode Exit fullscreen mode

While

fn main() {
    let a = [10, 20, 30, 40, 50];
    let mut index = 0;

    while index < 5 {
        println!("The value is: {}", a[index]);

        index += 1;
    }
}
Enter fullscreen mode Exit fullscreen mode

Handling input

use std::io;

fn main() {
    loop {
        println!("Please enter some number.");

        let mut number = String::new();

        io::stdin()
            .read_line(&mut number)
            .expect("Failed to read line");

        let number: u32 = match number.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };

        println!("Your number: {}", number);

        break;
    }
}
Enter fullscreen mode Exit fullscreen mode

Exercise

Task

User enters 3 numbers, which correspond to the sizes of triangle sides. The programm computes circumference, area, whether the triangle is equilateral, isosceles or right.

Solution

Triangle


Check out my learning Rust repo on GitHub!

Top comments (3)

Collapse
 
islamuddin profile image
islamuddin

Thanks a lost , Sir Petr Janik for great work, we are 34 rust coders following you by WhatsApp group here.
chat.whatsapp.com/CkJTxjlYCfhEQsm0...

Collapse
 
petr7555 profile image
Petr Janik

I am so glad you found my article helpful!

Collapse
 
islamuddin profile image
islamuddin

yes sir.