// Scalar Types
fn scalar_types_demo() {
    // Integers
    let a: i32 = 10;
    let b: u64 = 1000;

    // Floating-point numbers
    let x: f64 = 3.14159;
    let y: f32 = 2.71828;

    // Booleans
    let is_active: bool = true;

    // Characters
    let letter: char = 'A';

    println!("Integer a: {}", a);
    println!("Unsigned integer b: {}", b);
    println!("Floating point x: {}", x);
    println!("Floating point y: {}", y);
    println!("Boolean is_active: {}", is_active);
    println!("Character letter: {}", letter);
}

// Compound Types (Tuples and Arrays)
fn compound_types_demo() {
    // Tuple: Can hold multiple data types
    let tup: (i32, f64, char) = (500, 6.4, 'a');
    let (x, y, z) = tup;
    println!("Tuple values: x = {}, y = {}, z = {}", x, y, z);

    // Array: Fixed size and same data type
    let arr: [i32; 3] = [1, 2, 3];
    println!("Array values: {:?}", arr);
}

// Custom Types (Structs and Enums)
struct Rectangle {
    width: u32,
    height: u32,
}

fn area(rect: &Rectangle) -> u32 {
    rect.width * rect.height
}

enum Direction {
    North,
    South,
    East,
    West,
}

fn describe_direction(direction: Direction) {
    match direction {
        Direction::North => println!("Going North!"),
        Direction::South => println!("Going South!"),
        Direction::East => println!("Going East!"),
        Direction::West => println!("Going West!"),
    }
}

// Functions: Basic and with Return
fn add(x: i32, y: i32) -> i32 {
    x + y
}

fn multiply(x: i32, y: i32) -> i32 {
    x * y
}

fn main() {
    // Demo for scalar and compound types
    scalar_types_demo();
    compound_types_demo();

    // Custom Types demo (Struct and Enum)
    let rect = Rectangle { width: 30, height: 50 };
    println!("Area of rectangle: {}", area(&rect));

    let direction = Direction::North;
    describe_direction(direction);

    // Function call with return value
    let sum = add(10, 20);
    let product = multiply(10, 20);
    println!("Sum: {}", sum);
    println!("Product: {}", product);
}
 
by

Rust Online Compiler

Write, Run & Share Rust code online using OneCompiler's Rust online compiler for free. It's one of the robust, feature-rich online compilers for Rust language. Getting started with the OneCompiler's Rust editor is easy and fast. The editor shows sample boilerplate code when you choose language as Rust and start coding.