> > Main
Threads
rustDemo ( 2410264 ) - rustDemo ( 2410264 ) stack: main.closure1(src/main.rs:928) main(src/main.rs:1519)
/* src */
use log::{Record, Level, Metadata, LevelFilter, SetLoggerError};
use gag::BufferRedirect;
use std::fmt::{Debug};
use std::io::{self, Read, Write};
use std::fs::OpenOptions;
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::thread;
use std::fmt::Display;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio; // Asynchronous runtime
use tokio::time::sleep;
use std::error::Error;
use std::str::FromStr;
use anyhow::{Context as AnyhowContext, Result};

/// An asynchronous function that may fail
async fn might_fail(success: bool) -> Result<String, Box<dyn Error>> {
    if success {
        Ok("Everything went well!".to_string())
    } else {
        Err("Something went wrong.".into())
    }
}

// =============================================================================
// 1. Diverging Functions (Never Type) - Functions that never return
// =============================================================================

/// Diverging function example 1: panic function with where clause
/// This function accepts any displayable type but never returns normally
fn panic_with_message<T>(message: T) -> !
where
    T: Display + Send + Sync + 'static,
{
    panic!("Critical error: {}", message);
}

/// Diverging function example 2: infinite server loop function
/// This function simulates a server that runs forever
fn run_infinite_server<H>(handler: H) -> !
where
    H: Fn(&str) -> String + Send + Sync + 'static,
{
    let mut counter = 0;
    loop {
        counter += 1;
        let request = format!("request_{}", counter);
        let response = handler(&request);
        println!("Processed: {} -> {}", request, response);

        // Simulate processing delay
        std::thread::sleep(Duration::from_millis(100));

        // In real applications, this would be an actual network service loop
        if counter >= 5 {
            // For demo purposes, we exit after 5 iterations, but the type system considers this unreachable
            std::process::exit(0);
        }
    }
}

/// Diverging function example 3: error handling function
/// Called when encountering unrecoverable errors
fn handle_fatal_error<E>(error: E) -> !
where
    E: std::error::Error + Display + Send + Sync + 'static,
{
    eprintln!("Fatal error occurred: {}", error);
    eprintln!("Stack trace: {:?}", std::backtrace::Backtrace::capture());
    std::process::exit(1);
}

// =============================================================================
// 2. Async Functions - Automatically wrapped in Future
// =============================================================================

/// Async function example 1: simple async computation
/// Return type automatically becomes impl Future<Output = i32>
async fn calculate_async(x: i32, y: i32) -> i32 {
    // Simulate async computation
    sleep(Duration::from_millis(100)).await;
    x + y
}

/// Async function example 2: async data fetching
/// Demonstrates more complex async operations
async fn fetch_user_data(user_id: u64) -> Result<String, String> {
    println!("Fetching data for user {}", user_id);

    // Simulate network delay
    sleep(Duration::from_millis(200)).await;

    // Simulate success or failure scenarios
    if user_id == 0 {
        Err("Invalid user ID".to_string())
    } else {
        Ok(format!("User data for ID: {}", user_id))
    }
}

/// Async function example 3: generic async function
/// Shows how async functions can be combined with generics
async fn process_async_data<T, F>(data: T, processor: F) -> String
where
    T: Display + Send,
    F: Fn(T) -> String + Send,
{
    // Async wait
    sleep(Duration::from_millis(50)).await;

    let processed = processor(data);
    format!("Async processed: {}", processed)
}

/// Custom Future implementation example
/// Shows how to manually implement the Future trait
struct CustomFuture {
    completed: bool,
}

impl CustomFuture {
    fn new() -> Self {
        CustomFuture { completed: false }
    }
}

impl Future for CustomFuture {
    type Output = String;

    fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
        if self.completed {
            Poll::Ready("Custom future completed!".to_string())
        } else {
            self.completed = true;
            Poll::Pending
        }
    }
}

// =============================================================================
// 3. Generic Returns - impl Trait and concrete generic types
// =============================================================================

/// Generic return example 1: returning impl Trait
/// Callers don't need to know the concrete return type, only that it implements the specified trait
fn create_iterator() -> impl Iterator<Item = i32> {
    (0..10).map(|x| x * x)
}

/// Generic return example 2: returning impl Display
/// Can return any type that implements the Display trait
fn format_value(use_string: bool) -> impl Display {
    if use_string {
        "Hello, World!".to_string()
    } else {
        "Hello, World!".to_string() // Note: in impl Trait, all branches must return the same type
    }
}

/// Generic return example 3: returning impl Future (async version)
/// Combines async and impl Trait
fn create_async_task(delay_ms: u64) -> impl Future<Output = String> {
    async move {
        sleep(Duration::from_millis(delay_ms)).await;
        format!("Task completed after {}ms", delay_ms)
    }
}

/// Generic return example 4: concrete generic type return
/// Uses concrete generic parameters
fn create_collection<T>(items: Vec<T>) -> Vec<T>
where
    T: Clone,
{
    let mut result = items.clone();
    result.extend_from_slice(&items);
    result
}

/// Generic return example 5: complex impl Trait return
/// Returns a type that implements multiple traits
fn create_debug_display<T>(value: T) -> impl Display + std::fmt::Debug + Send
where
    T: Display + std::fmt::Debug + Send + 'static,
{
    format!("Wrapped: {}", value)
}

/// Generic return example 6: closure return
/// Returns a closure, which is also impl Trait
fn create_multiplier(factor: i32) -> impl Fn(i32) -> i32 {
    move |x| x * factor
}

/// Generic return example 7: conditional return of different impl Trait
/// Uses Box to unify different types
fn create_conditional_iterator(use_range: bool) -> Box<dyn Iterator<Item = i32>> {
    if use_range {
        Box::new(0..5) as Box<dyn Iterator<Item = i32>>
    } else {
        Box::new(vec![1, 3, 5, 7, 9].into_iter()) as Box<dyn Iterator<Item = i32>>
    }
}

// =============================================================================
// Error type definition (for diverging function demonstration)
// =============================================================================

#[derive(Debug)]
struct CustomError {
    message: String,
}

impl std::fmt::Display for CustomError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "CustomError: {}", self.message)
    }
}

impl std::error::Error for CustomError {}

// Additional test functions showing more usage patterns
#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_async_functions() {
        let result = calculate_async(2, 3).await;
        assert_eq!(result, 5);

        let user_data = fetch_user_data(456).await;
        assert!(user_data.is_ok());
    }

    #[test]
    fn test_generic_returns() {
        let squares: Vec<i32> = create_iterator().take(3).collect();
        assert_eq!(squares, vec![0, 1, 4]);

        let multiplier = create_multiplier(2);
        assert_eq!(multiplier(5), 10);
    }

    #[test]
    fn test_impl_trait_bounds() {
        let debug_display = create_debug_display(42);
        let display_str = format!("{}", debug_display);
        assert!(display_str.contains("42"));
    }
}

macro_rules! my_file_println {
    ($file_path:expr) => {
        {
            let path = Path::new($file_path);
            let mut file = OpenOptions::new()
                .create(true)
                .append(true)
                .open(path)
                .unwrap();

            writeln!(file).unwrap(); // only write a new line
        }
    };
    ($file_path:expr, $($arg:tt)*) => {
        {
            let path = Path::new($file_path);
            let mut file = OpenOptions::new()
                .create(true)
                .append(true)
                .open(path)
                .unwrap();

            writeln!(file, $($arg)*).unwrap();
        }
    }
}

macro_rules! my_file_println2 {
    () => {
        {
            let path = Path::new("/a/ete/bbb.log");
            let mut file = OpenOptions::new()
                .create(true)
                .append(true)
                .open(path)
                .unwrap();

            writeln!(file).unwrap();
        }
    };
    ($($arg:tt)*) => {
        {
            let path = Path::new("/a/ete/bbb.log");
            let mut file = OpenOptions::new()
                .create(true)
                .append(true)
                .open(path)
                .unwrap();

            writeln!(file, $($arg)*).unwrap();
        }
    }
}

#[derive(Debug)]
struct MyStruct {
    value: i32,
}

mod module_a {
    pub fn function_a(arg: i32) -> i32 /*comment2*/ {
        println!("entering Function A");
        let result = super::module_b::function_b(arg);
        println!("result {}", result);
        println!("Exiting function_a");
        result + 1
    }
}

mod module_b {
    pub fn function_b(arg: i32) -> i32 {
        println!("Inside Function B");
        let result = arg * 2;
        println!("result {}", result);
        result
    }
}

mod module_c {
    pub fn function_c(arg: i32) -> i32 {
        println!("Entering function_c");

        let result = super::module_d::function_d(arg);
        println!("result {}", result);
        println!("Exiting function_c");

        return result + 1
    }
}

mod module_d {
    pub fn function_d(arg: i32) -> i32 {
        let result = arg * 2;
        println!("function_d result {}", result);
        if (is_zero2(1) || is_zero1(1)) {
            return result;
        }
        result
    }

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

    fn noRet(n: i32) {
        match n {
            0 => return,
            _ => (),
        }
    }

    fn noRet2() {
        println!("noRet2");
        return;
    }

    fn is_zero1(n: i32) -> bool {
        let example_result: i32 = add(1, 2);
        // let return_type = std::any::type_name_of_val(&example_result); // type_name_of_val is unstable library feature
        // let return_type = std::any::type_name::<add>(); // bad
        let return_type = std::any::type_name::<fn(i32, i32) -> i32>(); // ok, return_type = 'fn(i32, i32) -> i32'
        println!("Return type: {}", return_type);

        println!("Inside Function is_zero1");
        let mut result = false;
        if n == 0 {
            result = true;
        } else {
            result = false;
        }
        // result // some comments 1
        return result // ok: some comments 2
    }

    fn is_zero2(n: i32) -> bool {
        is_zero1(2);

        noRet2();

        println!("Inside Function is_zero2");
        noRet(0);

        let a_bool = match n {
            0 => match n {
                0 => true,
                _ => false,
            },
            _ => {
                if true {
                    true
                } else {
                    false
                }
            }
        };
        println!("Inside Function is_zero2: a_bool: {}", a_bool);

        let b_bool = if !a_bool {
            match n {
                0 => true,
                _ => false,
            }
        } else {
            match n {
                1 => true,
                _ => false,
            }
        };

        let mut res = false;

        let res2 = if !b_bool {
            match n {
                0 => true,
                _ => false,
            }
        } else {
            res = match n {
                1 => true,
                _ => false,
            };
            res
        };

        if res && res2 {
            true
        } else {
            false
        }
    }

    fn is_zero3(n: i32) -> bool {
        println!("Inside Function is_zero3");
        match n {
            0 => true,
            _ => return false,
        }
    }

    fn has_zero(nums: &[i32]) -> bool {
        for &num in nums {
            if num == 0 {
                return true;
                return true;
            }
        }
        return false;
        false
    }

    fn has_zero2(nums: &[i32]) -> bool {
        for &num in nums {
            if num == 0 {
                match num {
                    0 => return true,
                    _ => break,
                }
            }
        }
        return false;
        false
    }

    fn count_zeros(nums: &[i32]) -> usize {
        nums.iter()
            .filter(|&&num| if num == 0 { true } else { false })
            .count()
    }
}

fn outer_function() -> i32 {
    fn inner_function() -> i32 {
        println!("Inside inner_function");
        fn inner_inner_function() -> i32 {
            println!("Inside inner_inner_function");
            return 10;
        }
        return inner_inner_function();
    }

    let closure = |x: i32| -> i32 {
        println!("Inside closure");
        fn inner_function_in_closure() -> i32 {
            println!("Inside inner_function_in_closure");
            return 10;
        };
        return x * inner_function_in_closure();
    };

    let value = inner_function();
    let double_value = closure(value);

    double_value
}

struct MyDefaultStruct {
    my_instance_variable: i32,
}

impl MyDefaultStruct {
    fn new() -> Self {
        Self {
            my_instance_variable: 43,
        }
    }
}

impl Default for MyDefaultStruct {
    fn default() -> Self {
        Self {
            my_instance_variable: 42,
        }
    }
}

enum MyEnum {
    Variant1(i32),
    Variant2(f64),
    Variant3(String),
}

fn get_enum_variant(variant: u8) -> MyEnum {
    match variant {
        1 => MyEnum::Variant1(42),
        2 => MyEnum::Variant3("Hello, world!".to_owned()),
        _ => MyEnum::Variant2(3.14),
    }
}

#[repr(C)]
union MyUnion {
    i: i32,
    f: f64,
}

fn get_union_variant(variant: u8) -> MyUnion {
    match variant {
        1 => MyUnion { i: 42 },
        _ => MyUnion { f: 3.14 },
    }
}

lazy_static::lazy_static! {
    static ref MY_STATIC_VARIABLE: i32 = {
        println!("Initializing static variable...");

        // Perform some computations or statements
        let result = expensive_computation();

        println!("Static variable initialized.");

        result // Return the computed value
    };
}

fn expensive_computation() -> i32 {
    // Simulate some expensive computation
    println!("Performing expensive computation...");
    42
}

fn returns_integer() -> i32 {
    42
}

fn returns_bool() -> bool {
    true
}

fn returns_tuple() -> (i32, f64) {
    (42, 3.14)
}

fn returns_array() -> [i32; 3] {
    [1, 2, 3]
}

fn returns_reference(input: &str) -> &str {
    input
}

fn returns_function() -> fn(i32) -> i32 {
    fn square(x: i32) -> i32 {
        x * x
    }
    square
}

#[derive(Debug)]
enum AnEnum {
    Variant1(u32),
    Variant2(bool),
    Variant3(String),
}

//#[derive(Debug)] // bad: the Debug trait cannot be derived for unions in Rust. This is because unions are a special type of struct that can only hold one value at a time, and the Debug trait requires all fields of a struct to be printable. Since a union can only have one field at a time, it cannot implement the Debug trait.
#[repr(C)] // ok
union AnotherUnion {
    field1: u32,
    field2: bool,
    field3: [u8; 4],
}

#[derive(Debug)]
struct MyTuple(u32, bool, [u8; 4]);

fn control_flow1() -> String {
    let power = 0.5;

    fmtools::format! {
        "At "
        if power >= 1.0 { "full" }
        else { {power * 100.0:.0}"%" }
        " power"
    }
}

fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>());
}

// This function takes an i32 and returns an i32
fn top_function(num: i32) -> i32 {
    println!("In top_function with num: {}", num);
    let intermediate_result = middle_function(num);
    return intermediate_result + 10; // Adds 10 to the result from middle_function

    println!("\n=== dead code here is also ok ===");
}

// This function takes an i32 and returns an i32
fn middle_function(num: i32) -> i32 {
    println!("In middle_function with num: {}", num);
    let squared = square(num);
    print_message(); // Calls a function that doesn't return a value
    return squared; // Returns the squared value
}

// This function takes an i32 and returns its square
fn square(num: i32) -> i32 {
    println!("In square with num: {}", num);
    num * num // Returns the square of num
}

// This function takes no parameters and doesn't return a value
fn print_message() {
    println!("This is a message from print_message.");

    let f1 = || 42;
    let f2 = |x: f64| x * 2.0;
    let f3 = |x: i8| -> i16 { x as i16 * 10 };
    let f4 = |x| (x,);
    let f5 = |a, b| (a, b, a + b);
    let f6 = || String::from("hello");
    let name = "Alice";
    let f7 = || name;
    let mut value = 123;
    let mut f8 = || {
        value += 1;
        value
    };
    let f9 = |x: i32| if x > 0 { Some(x) } else { None };
    let f10 = |x: i32| if x == 0 { Err("zero") } else { Ok(1.0 / x as f64) };
    let f11 = |n| vec![n; 3];
    let f12 = || {
        use std::collections::HashMap;
        let mut map = HashMap::new();
        map.insert("k", 100);
        map
    };
    let f13 = || |x| x + 1;
    let f14 = |x| Box::new(x * 3);
    let f15 = |x: i32| -> Box<dyn std::fmt::Debug> { Box::new(x * 2) };
    struct Point { x: i32, y: i32 }
    let f16 = |x, y| Point { x, y };
    let f17 = || {};
    let z = 77;
    let f18 = move || z * 100;

    println!("f1: {}", f1());
    println!("f2: {}", f2(0.5));
    println!("f3: {}", f3(8));
    println!("f4: {:?}", f4(6));
    println!("f5: {:?}", f5(3, 4));
    println!("f6: {}", f6());
    println!("f7: {}", f7());
    println!("f8: {}", f8());
    println!("f9: {:?}", f9(-4));
    println!("f10: {:?}", f10(0));
    println!("f11: {:?}", f11(7));
    println!("f12: {:?}", f12());
    println!("f13: {}", f13()(8));
    println!("f14: {:?}", f14(5));
    println!("f15: {:?}", f15(11));
    println!("f16: ({}, {})", f16(8, 9).x, f16(8, 9).y);
    println!("f17: {:?}", f17());
    println!("f18: {}", f18());

    return ();
}

fn doSomeAssert() {
    // Variable declarations
    let x = 5;
    let y = 10;
    let z = 5;

    // Assert that x is true (non-zero)
    assert!(x != 0, "x should not be zero");

    // Assert that two values are equal
    assert_eq!(x, z, "x and z should be equal");

    // Assert that two values are not equal
    assert_ne!(x, y, "x and y should not be equal");

    // Testing with expressions
    let sum = x + y;
    assert_eq!(sum, 15, "The sum of x and y should be 15");

    // A more complex assertion
    let condition = (x * 2) == y;
    assert!(condition, "x * 2 should be equal to y");

    // Assert panic condition
    let result = std::panic::catch_unwind(|| {
        assert!(false, "This assert will panic");
    });

    assert!(result.is_err(), "The assert inside should panic");

    println!("All assertions passed!");

}

#[derive(Debug)]
struct Point { x: i32, y: i32 }

#[derive(Debug)]
enum AnotherEnum {
    A(i32),
    B { x: i32 }
}

fn args_demo(
    x: i32,                             // 1. identifier pattern
    y: &i32,                            // 2. reference pattern
    (a, b): (i32, i32),                 // 3. tuple pattern
    Point { x: px, y: py }: Point,      // 4. struct pattern
    val: AnotherEnum,                   // 5. enum variant pattern
    slice: &[i32],                      // 6. array / slice pattern
    _: i32,                             // 7. wildcard pattern
    literal_val: i32,                   // 8. literal pattern
    ((p, q), Point { x: nx, y: ny }): ((i32, i32), Point) // 9. nested / combination pattern
) {
    println!("identifier: x={}, reference: y={}", x, y);
    println!("tuple: a={}, b={}", a, b);
    println!("struct: px={}, py={}", px, py);

    match val {
        AnotherEnum::A(enum_val) => println!("enum A val: {}", enum_val),
        AnotherEnum::B { x } => println!("enum B x: {}", x),
    }

    if slice.len() >= 2 {
        println!("slice: m={}, n={}", slice[0], slice[1]);
    }

    if literal_val == 42 {
        println!("literal value is 42");
    } else {
        println!("literal value is not 42, got: {}", literal_val);
    }

    println!("nested tuple+struct: p={}, q={}, nx={}, ny={}", p, q, nx, ny);
}

fn is_unit<T: std::any::Any>(val: &T) -> bool {
    val.type_id() == std::any::TypeId::of::<()>()
}

// =============================================================================
// Main function and tests
// =============================================================================

enum MyOption {
    None,
    Some(i32),
}

struct Pair(i32, i32);

fn never_returns() {
    panic!("this never returns")
}

fn getNumber(string: &str) -> Result<u32> {
    let number: u32 = string.parse().with_context(|| "not a number".to_string())?;
    Ok(number)
}

fn capture_and_modify_output() -> io::Result<()> {
    // Redirect stdout to a buffer
    let redirect = BufferRedirect::stdout()?;

    // Execute the output that needs to be captured
    println!("First line of output");
    println!("Second line of output");
    println!("This is the third line");
    print!("Output without newline");
    println!(); // Add a newline
    println!("Last line");

    // Restore stdout and get the captured content
    let mut captured_output = String::new();
    redirect.into_inner().read_to_string(&mut captured_output)?;

    // Process the captured output: add "aaa" at the end of each line
    let lines: Vec<&str> = captured_output.lines().collect();

    // Print the modified output
    for line in lines {
        println!("{}aaa", line);
    }

    Ok(())
}

fn capture_and_modify_output2() {
    // Redirect stdout to a buffer
    let redirect = match BufferRedirect::stdout() {
        Ok(r) => r,
        Err(e) => {
            eprintln!("Error: failed to redirect stdout: {}", e);
            return;
        }
    };

    // Execute the output that needs to be captured
    println!("First line of output");
    println!("Second line of output");
    println!("This is the third line");
    print!("Output without newline");
    println!(); // Add a newline
    println!("Last line");

    // Restore stdout and get the captured content
    let mut captured_output = String::new();
    match redirect.into_inner().read_to_string(&mut captured_output) {
        Ok(_) => {},
        Err(e) => {
            eprintln!("Error: failed to read captured output: {}", e);
            return;
        }
    }

    // Process the captured output: add "aaa" at the end of each line
    let lines: Vec<&str> = captured_output.lines().collect();

    // Print the modified content
    for line in lines {
        println!("{}aaa", line);
    }
}

fn example_function() {
    let closure = || {
        let example = ExampleStruct::new();
        example.do_something();
    };
    closure();
}

struct ExampleStruct;

impl ExampleStruct {
    fn new() -> Self {
        ExampleStruct
    }

    fn do_something(&self) {
        Self::static_method();
    }

    fn static_method() {
        println!("static_method");
    }
}

fn add_one(x: i32) -> i32 {
    x + 1
}

fn get_function() -> fn(i32) -> i32 {
    add_one
}

fn make_adder(y: i32) -> impl Fn(i32) -> i32 {
    move |x| x + y
}

fn choose_adder(flag: bool) -> Box<dyn Fn(i32) -> i32> {
    if flag {
        Box::new(|x| x + 1)
    } else {
        Box::new(|x| x + 100)
    }
}

#[tokio::main]
async fn main() {

    let f = get_function();
    println!("f(5) = {}", f(5));

    let add_five = make_adder(5);
    println!("10 + 5 = {}", add_five(10));

    let f = choose_adder(true);
    println!("f(10) = {}", f(10));

    example_function();

    // capture_and_modify_output().unwrap();
    // capture_and_modify_output2();

    // No log print out in console if no impl of crate log is initialized when using log::error! ...
    log::error!("This is an error");
    log::trace!("Initialized Rust");
    log::debug!("Address is {:p}", main as *const ());
    log::info!("Did you know? {} = {}", "1 + 1", 2);
    log::warn!("Don't log sensitive information!");
    log::error!("Nothing more to say");

    println!("{:?}", getNumber("42"));
    println!("{:?}", getNumber("abc"));

    println!("--- Async Error Handling Demo ---");

    // Successful case
    match might_fail(true).await {
        Ok(msg) => println!("Success: {}", msg),
        Err(e) => println!("Error: {}", e),
    }

    // Error case
    // match might_fail(false).await {
    //     Ok(msg) => println!("Success: {}", msg),
    //     Err(e) => println!("Error: {}", e),
    // }

    let point = Point { x: 10, y: 20 };
    let another_point = Point { x: 30, y: 40 };
    let enum_val = AnotherEnum::A(100);
    let slice_data = [1, 2, 3, 4];

    args_demo(
        5,                              // x: i32
        &15,                            // y: &i32
        (7, 8),                         // (a, b): (i32, i32)
        point,                          // Point struct
        enum_val,                       // AnotherEnum
        &slice_data[..2],               // slice
        0,                              // wildcard (any value)
        42,                             // literal value
        ((1, 2), another_point)         // nested pattern
    );

    let input = 5;

    // Calling the top-level function
    let result = top_function(input);
    println!("Final result: {}", result);

    my_file_println!("/a/ete/log.txt", "This is a log message: {}", 42);
    my_file_println!("/a/ete/log.txt", "Another message with variable: {}, and number: {}", "data", 100);
    my_file_println!("/a/ete/log.txt");

    println!("hello");
    eprintln!("world");

    let my_struct = MyStruct { value: 42 };

    println!("{:?}", &my_struct);

    my_file_println2!("This is a log message: {}", 42);
    my_file_println2!("Another message with variable: {}, and number: {}", "data", 100);
    my_file_println2!("/a/ete/log.txt");

    my_file_println2!("{:?}", &my_struct);

    let v1 = vec![1i32,2,3];
    let v2 = 1_i32;
    let v3 = "hello";
    let v4 = 42;

    if v4 > 0 {
        println!("Positive number");
    }

    if v4 > 0 {println!("Positive number");}

    for i in 0..5 {
        println!("{}", i);
    }

    let mut count = 0;

    while count < 5 {
        println!("{}", count);
        count += 1;
    }

    let mut iter = (0..10).into_iter();
    while let Some(i) = iter.next() {
        println!("{}", i);
    }

    let x: Option<i32> = None;

    if let Some(i) = x {
        println!("Got: {}", i);
    } else {
        println!("Nothing here");
    }

    // Data types demonstration
    let integer: i32 = 42; // Integer type
    let float: f64 = 3.14159; // Floating-point type
    let boolean: bool = true; // Boolean type
    let character: char = 'R'; // Character type
    let string: &str = "Hello, Rust!"; // String slice

    let value = Some(42);

    match value {
        None => println!("Got nothing"),                // literal_pattern
        Some(x) if x > 40 => println!("Big {}", x),     // identifier_pattern + guard
        Some(0) => println!("Zero"),                    // literal_pattern
        Some(n @ 1..=10) => println!("Small {}", n),    // range_pattern + at_pattern
        Some(_) => println!("Something else"),          // wildcard_pattern
    }


    let (mut x, y) = (10, 20);
    x += 5;
    println!("x = {}, y = {}", x, y);

    let mut x = 10;

    x += 5;
    println!("x after += 5: {}", x);

    x -= 3;
    println!("x after -= 3: {}", x);

    x *= 2;
    println!("x after *= 2: {}", x);

    x /= 2;
    println!("x after /= 2: {}", x);

    x %= 3;
    println!("x after %= 3: {}", x);

    x |= 2;
    println!("x after |= 2: {}", x);

    x &= 1;
    println!("x after &= 1: {}", x);

    x ^= 3;
    println!("x after ^= 3: {}", x);

    let mut y = 1u8;
    y <<= 2;
    println!("y after <<= 2: {}", y);

    y >>= 1;
    println!("y after >>= 1: {}", y);

    // Printing data types
    println!("Integer: {}, Float: {:.2}, Boolean: {}, Character: '{}', String: {}",
             integer, float, boolean, character, string);

    // Conditional statement demonstration
    if integer > 50 {
        println!("The integer is greater than 50.");
    } else if integer > 30 {
        println!("The integer is greater than 30 but less than or equal to 50.");
    } else {
        println!("The integer is less than or equal to 30.");
    }

    // Loop demonstration with break and continue
    let mut count = 0;
    while count < 10 {
        count += 1;
        if count == 5 {
            continue; // Skip the number 5
        }
        println!("Current count: {}", count);
        if count == 8 {
            break; // Exit the loop when count reaches 8
        }
    }

    // If statement

    // if true
    //     println!("if true");
    // else
    //     println!("if false");

    if true {
        println!("if true");
    } else {
        println!("if false");
    }

    // For loop with range

    // for i in 0..5
    //     println!("For loop iteration: {}", i);

    for i in 0..5 {
        println!("For loop iteration: {}", i);
    }


    // Pattern matching demonstration
    let number = 2;

    match number {
        1 => println!("One"),
        2 => println!("Two"),
        3 => println!("Three"),
        _ => println!("Other"),
    }

    let ttt = match number {
        1 => return,
        _ => (),
    };

    let ret = match number {
        1 => "One",
        2 => "Two",
        3 => "Three",
        _ => "Other",
    };

    let ret = match number {
        1 => {let a = "One"; a},
        2 => {let a = "Two"; a},
        3 => {let a = "Three"; a},
        _ => {let a = "Other"; a},
    };

    if (&ret as &dyn std::any::Any).type_id() == std::any::TypeId::of::<()>() {
        println!("ret is unit");
    } else {
        println!("ret is not unit");
    }

    match number {
        1 => "One",
        2 => "Two",
        3 => "Three",
        _ => "Other",
    };

    let number_str = match number {
        1 => "One",
        2 => "Two",
        3 => "Three",
        _ => "Other",
    };
    println!("number: {} number_str: {}", number, number_str);

    let result1 = module_a::function_a(10);
    println!("result1 {}", result1);
    //if 8==8 {return;}
    let result2 = module_c::function_c(10);
    println!("result2: {}", result2);

    // Sigle line closure
    let add = |a: i32, b: i32| a + b;
    let add = |a: i32, b: i32| { a + b };
    println!("Sigle line closure: {}", add(1, 2));

    // Embedded closure
    let y = 10;
    let closure = |x: i32| {
        let inner = |n: i32| n + y;
        return inner(x);
    };
    println!("{}", closure(5));

    let process_tuple = |(x, y): (i32, i32)| x + y;

    let no_param = || println!("no_param");

    let mut mut_binding = |mut x: i32| {
        x += 1;
        println!("mut_binding: {}", x);
    };

    let ref_param = |&x: &i32| println!("ref_param: {}", x);
    let mut y = 10;
    let mut_ref_param = |&mut x: &mut i32| {
        println!("mut_ref_param: {}", x);
    };

    let closure = |opt: Option<i32>| {
        match opt {
            Some(value) => println!("Value: {}", value),
            None => println!("Got None"),
        }
    };

    closure(Some(42));
    closure(None);

    let tuple_struct_param = |opt: MyOption| {
        match opt {
            MyOption::Some(value) => println!("Value: {}", value),
            MyOption::None => println!("Got None"),
        }
    };

    tuple_struct_param(MyOption::Some(42));
    tuple_struct_param(MyOption::None);

    let tuple_param = |(a, b): (i32, i32)| println!("tuple_param: {} + {} = {}", a, b, a+b);

    let struct_param = |Point { x, y }: Point| println!("struct_param: x={}, y={}", x, y);

    let slice_param = |slice: &[i32]| {
        match slice {
            [first, second, ..] => {
                println!("slice_param: first={}, second={}", first, second);
            }
            _ => {
                println!("slice_param: slice too short");
            }
        }
    };

    let wildcard_param = |_ignored: i32| println!("wildcard_param");

    no_param();
    mut_binding(5);
    ref_param(&20);
    mut_ref_param(&mut y);
    tuple_param((3, 4));
    slice_param(&[1, 2, 3, 4]);
    wildcard_param(100);

    let result_closure = || {
        let x = 42;
        x // Implicit return in closure
    };
    println!("Result from closure: {}", result_closure());

    let result_if_else = if true {
        "Hello"
    } else {
        "World" // Implicit return in if-else expression
    };
    println!("Result from if-else: {}", result_if_else);

    let result_match = match 5 {
        1 => "One",
        2 => "Two",
        _ => "Other", // Implicit return in match arm
    };
    println!("Result from match: {}", result_match);

    let mut i = 0;
    let result_loop = loop {
        i += 1;
        if i >= 5 {
            break i; // Implicit return in loop body
        }
    };
    println!("Result from loop: {}", result_loop);

    let result_block: i32 = {
        let x = 10;
        let y = 20;
        x + y // Implicit return in block expression
    };
    println!("Result from block: {}", result_block);

    let result3 = outer_function();
    println!("result3: {}", result3);

    let my_enum = get_enum_variant(2);
    match my_enum {
        MyEnum::Variant1(i) => println!("Integer: {}", i),
        MyEnum::Variant2(f) => println!("Float: {}", f),
        MyEnum::Variant3(s) => println!("String: {}", s),
    }

    let my_union = get_union_variant(1);
    unsafe {
        println!("Integer: {}", my_union.i);
    }

    let pair = Pair(3, 7);

    match pair {
        Pair(x, y) if x == y => println!("Equal: {}", x),
        Pair(x, y) => println!("Not equal: {} vs {}", x, y),
    }

    let A = 1 == 0 else { return };
    println!("A: {}", A);

    let an_enum = AnEnum::Variant1(42);
    println!("{:?}", an_enum);

    let an_union = AnotherUnion { field1: 42 };
    // println!("{:?}", an_union); // bad
    unsafe {
        let a_struct = std::mem::transmute::<AnotherUnion, (u32,)>(an_union);
        println!("{:?}", a_struct.0);
    }

    let my_tuple = MyTuple(42, true, [0x12, 0x34, 0x56, 0x78]);
    println!("{:?}", my_tuple);

    let my_struct = MyDefaultStruct {
        my_instance_variable: 42,
    };
    let is_struct1 = std::mem::size_of_val(&my_struct) == std::mem::size_of::<MyDefaultStruct>(); // Note that this method is not foolproof, as other types may have the same size as a struct. However, it can be a useful heuristic for determining if a variable is a struct in many cases.
    println!("my_struct is a struct: {}", is_struct1);

    let result5 = control_flow1();
    println!("{}", result5);

    // Closure 1: Takes a string and returns its length
    let length_closure = |s: &str| -> usize {
        s.len() // The return value is the length of the string
    };

    // Closure 2: Takes two integers and returns their sum
    let sum_closure = |a: i32, b: i32| -> i32 {
        a + b // The return value is the sum of a and b
    };

    // Closure 3: Takes an integer and prints a message (no return value)
    let print_closure = |x: i32| {
        println!("The value is: {}", x);
        // Implicitly returns () (unit type), no explicit return
    };

    let diverging_closure = || -> ! {
        panic!("this closure never returns");
    };

    // let diverging_closure2 = || { let a = {panic!("this closure never returns")}; return a;};

    // let diverging_closure3 = || -> ! {
    //     let a = {panic!("this closure never returns")};
    //     return a;
    //     // return (); // bad
    // };

    // let diverging_closure4 = || {
    //     let a = {panic!("this closure never returns")};
    //     return a;
    //     return (); // ok
    // };

    // Using the closures
    let my_string = "Hello, Rust!";
    let length = length_closure(my_string);
    println!("Length of '{}' is {}", my_string, length);

    let a = 5;
    let b = 10;
    let sum = sum_closure(a, b);
    println!("Sum of {} and {} is {}", a, b, sum);

    let value = 42;
    print_closure(value); // Just prints the value

    // doSomeAssert();

    // Multi-threading demonstration with synchronization
    let counter = Arc::new(Mutex::new(0)); // Create an Arc and Mutex to share state
    let mut handles = vec![];

    for thread_id in 0..10 {
        let counter_clone = Arc::clone(&counter); // Clone Arc for each thread
        let handle = thread::spawn(move || {
            let mut num = counter_clone.lock().unwrap(); // Lock the mutex for safe access
            *num += 1; // Increment the counter
            println!("Thread {} incremented counter to {}", thread_id, *num);
            thread::sleep(Duration::from_millis(100)); // Simulate work with sleep
        });
        handles.push(handle);
    }

    // Waiting for all threads to complete
    for handle in handles {
        handle.join().unwrap();
    }

    // Print the final counter value
    println!("Final counter value: {}", *counter.lock().unwrap());

    println!("=== Rust Advanced Function Features Demo ===\n");

    // 1. Diverging functions demonstration
    println!("1. Diverging Functions Demo:");
    println!("Note: Diverging functions never return normally, so we only show their definitions");

    // Demonstrate how to use diverging functions (but we don't actually call them as they would terminate the program)
    println!("- panic_with_message: Can accept any Display type and panic");
    println!("- run_infinite_server: Simulates a server that runs forever");
    println!("- handle_fatal_error: Handles fatal errors and exits the program");

    // Show how diverging functions can be used in error handling
    let result = std::panic::catch_unwind(|| {
        if false { // Use false here to avoid actual panic
            panic_with_message("This would never return!");
        }
        "Normal execution"
    });
    println!("- Panic handling result: {:?}\n", result);

    // 2. Async functions demonstration
    println!("2. Async Functions Demo:");

    // Simple async computation
    let sum = calculate_async(5, 3).await;
    println!("- Async calculation: 5 + 3 = {}", sum);

    // Async data fetching
    match fetch_user_data(123).await {
        Ok(data) => println!("- Fetched: {}", data),
        Err(e) => println!("- Error: {}", e),
    }

    // Generic async function
    let processed = process_async_data(42, |x| format!("Number: {}", x)).await;
    println!("- {}", processed);

    // // Custom Future
    // let mut custom_future = CustomFuture::new();
    // // Multiple polls needed for completion
    // let result = custom_future.await;
    // println!("- {}", result);

    // // impl Future return
    // let task_result = create_async_task(150).await;
    // println!("- {}\n", task_result);

    // 3. Generic returns demonstration
    println!("3. Generic Returns Demo:");

    // impl Iterator
    let squares: Vec<i32> = create_iterator().collect();
    println!("- Squares: {:?}", squares);

    // impl Display
    let display_value = format_value(true);
    println!("- Display value: {}", display_value);

    // Concrete generic type
    let doubled_vec = create_collection(vec![1, 2, 3]);
    println!("- Doubled collection: {:?}", doubled_vec);

    // Complex impl Trait
    let debug_display = create_debug_display("Hello");
    println!("- Debug display: {} (Debug: {:?})", debug_display, debug_display);

    // Closure return
    let multiplier = create_multiplier(3);
    println!("- Multiplier result: 4 * 3 = {}", multiplier(4));

    // Conditional Iterator
    let range_iter: Vec<i32> = create_conditional_iterator(true).collect();
    let vec_iter: Vec<i32> = create_conditional_iterator(false).collect();
    println!("- Range iterator: {:?}", range_iter);
    println!("- Vec iterator: {:?}", vec_iter);

    println!("\n=== Demo Completed :) ===");

    // To demonstrate diverging functions, uncomment the following (but this will terminate the program):
    // panic_with_message("This is a diverging function!");

    // Or demonstrate the infinite server (this will run 5 times then exit):
    // run_infinite_server(|req| format!("Response to {}", req));

    return;

    println!("\n=== dead code here is ok ===");
}
Variables All
No.FromNameValue
NANANANA
Output All Filter Merge
ProcessThread Filter
2410264 rustDemo 2410292 rustDemo 2410289 rustDemo 2410288 rustDemo 2410283 rustDemo 2410264 rustDemo 2410291 rustDemo 2410290 rustDemo 2410287 rustDemo 2410286 rustDemo 2410285 rustDemo 2410284 rustDemo
No.PNPIDTIDTNMessage
1rustDemo24102642410264rustDemof(5) = 6
2rustDemo24102642410264rustDemo10 + 5 = 15
3rustDemo24102642410264rustDemof(10) = 11
4rustDemo24102642410264rustDemostatic_method
5rustDemo24102642410264rustDemoError: This is an error
6rustDemo24102642410264rustDemoTrace: Initialized Rust
7rustDemo24102642410264rustDemoDebug: Address is 0x55d1db74af80
8rustDemo24102642410264rustDemoInfo: Did you know? 1 + 1 = 2
9rustDemo24102642410264rustDemoWarn: Don't log sensitive information!
10rustDemo24102642410264rustDemoError: Nothing more to say
11rustDemo24102642410264rustDemoOk(42)
12rustDemo24102642410264rustDemoErr(not a number

Caused by:
invalid digit found in string)
13rustDemo24102642410264rustDemo--- Async Error Handling Demo ---
14rustDemo24102642410264rustDemoSuccess: Everything went well!
15rustDemo24102642410264rustDemoidentifier: x=5, reference: y=15
16rustDemo24102642410264rustDemotuple: a=7, b=8
17rustDemo24102642410264rustDemostruct: px=10, py=20
18rustDemo24102642410264rustDemoenum A val: 100
19rustDemo24102642410264rustDemoslice: m=1, n=2
20rustDemo24102642410264rustDemoliteral value is 42
21rustDemo24102642410264rustDemonested tuple+struct: p=1, q=2, nx=30, ny=40
22rustDemo24102642410264rustDemoIn top_function with num: 5
23rustDemo24102642410264rustDemoIn middle_function with num: 5
24rustDemo24102642410264rustDemoIn square with num: 5
25rustDemo24102642410264rustDemoThis is a message from print_message.
26rustDemo24102642410264rustDemof1: 42
27rustDemo24102642410264rustDemof2: 1
28rustDemo24102642410264rustDemof3: 80
29rustDemo24102642410264rustDemof4: (6,)
30rustDemo24102642410264rustDemof5: (3, 4, 7)
31rustDemo24102642410264rustDemof6: hello
32rustDemo24102642410264rustDemof7: Alice
33rustDemo24102642410264rustDemof8: 124
34rustDemo24102642410264rustDemof9: None
35rustDemo24102642410264rustDemof10: Err("zero")
36rustDemo24102642410264rustDemof11: [7, 7, 7]
37rustDemo24102642410264rustDemof12: {"k": 100}
38rustDemo24102642410264rustDemof13: 9
39rustDemo24102642410264rustDemof14: 15
40rustDemo24102642410264rustDemof15: 22
41rustDemo24102642410264rustDemof16: (8, 9)
42rustDemo24102642410264rustDemof17: ()
43rustDemo24102642410264rustDemof18: 7700
44rustDemo24102642410264rustDemoFinal result: 35
45rustDemo24102642410264rustDemohello
46rustDemo24102642410264rustDemoworld
47rustDemo24102642410264rustDemoMyStruct { value: 42 }
48rustDemo24102642410264rustDemoPositive number
49rustDemo24102642410264rustDemoPositive number
50rustDemo24102642410264rustDemo0
51rustDemo24102642410264rustDemo1
52rustDemo24102642410264rustDemo2
53rustDemo24102642410264rustDemo3
54rustDemo24102642410264rustDemo4
55rustDemo24102642410264rustDemo0
56rustDemo24102642410264rustDemo1
57rustDemo24102642410264rustDemo2
58rustDemo24102642410264rustDemo3
59rustDemo24102642410264rustDemo4
60rustDemo24102642410264rustDemo0
61rustDemo24102642410264rustDemo1
62rustDemo24102642410264rustDemo2
63rustDemo24102642410264rustDemo3
64rustDemo24102642410264rustDemo4
65rustDemo24102642410264rustDemo5
66rustDemo24102642410264rustDemo6
67rustDemo24102642410264rustDemo7
68rustDemo24102642410264rustDemo8
69rustDemo24102642410264rustDemo9
70rustDemo24102642410264rustDemoNothing here
71rustDemo24102642410264rustDemoBig 42
72rustDemo24102642410264rustDemox = 15, y = 20
73rustDemo24102642410264rustDemox after += 5: 15
74rustDemo24102642410264rustDemox after -= 3: 12
75rustDemo24102642410264rustDemox after *= 2: 24
76rustDemo24102642410264rustDemox after /= 2: 12
77rustDemo24102642410264rustDemox after %= 3: 0
78rustDemo24102642410264rustDemox after |= 2: 2
79rustDemo24102642410264rustDemox after &= 1: 0
80rustDemo24102642410264rustDemox after ^= 3: 3
81rustDemo24102642410264rustDemoy after <<= 2: 4
82rustDemo24102642410264rustDemoy after >>= 1: 2
83rustDemo24102642410264rustDemoInteger: 42, Float: 3.14, Boolean: true, Character: 'R', String: Hello, Rust!
84rustDemo24102642410264rustDemoThe integer is greater than 30 but less than or equal to 50.
85rustDemo24102642410264rustDemoCurrent count: 1
86rustDemo24102642410264rustDemoCurrent count: 2
87rustDemo24102642410264rustDemoCurrent count: 3
88rustDemo24102642410264rustDemoCurrent count: 4
89rustDemo24102642410264rustDemoCurrent count: 6
90rustDemo24102642410264rustDemoCurrent count: 7
91rustDemo24102642410264rustDemoCurrent count: 8
92rustDemo24102642410264rustDemoif true
93rustDemo24102642410264rustDemoFor loop iteration: 0
94rustDemo24102642410264rustDemoFor loop iteration: 1
95rustDemo24102642410264rustDemoFor loop iteration: 2
96rustDemo24102642410264rustDemoFor loop iteration: 3
97rustDemo24102642410264rustDemoFor loop iteration: 4
98rustDemo24102642410264rustDemoTwo
99rustDemo24102642410264rustDemoret is not unit
100rustDemo24102642410264rustDemonumber: 2 number_str: Two
101rustDemo24102642410264rustDemoentering Function A
102rustDemo24102642410264rustDemoInside Function B
103rustDemo24102642410264rustDemoresult 20
104rustDemo24102642410264rustDemoresult 20
105rustDemo24102642410264rustDemoExiting function_a
106rustDemo24102642410264rustDemoresult1 21
107rustDemo24102642410264rustDemoEntering function_c
108rustDemo24102642410264rustDemofunction_d result 20
109rustDemo24102642410264rustDemoReturn type: fn(i32, i32) -> i32
110rustDemo24102642410264rustDemoInside Function is_zero1
111rustDemo24102642410264rustDemonoRet2
112rustDemo24102642410264rustDemoInside Function is_zero2
113rustDemo24102642410264rustDemoInside Function is_zero2: a_bool: true
114rustDemo24102642410264rustDemoresult 20
115rustDemo24102642410264rustDemoExiting function_c
116rustDemo24102642410264rustDemoresult2: 21
117rustDemo24102642410264rustDemoSigle line closure: 3
118rustDemo24102642410264rustDemo15
119rustDemo24102642410264rustDemoValue: 42
120rustDemo24102642410264rustDemoGot None
121rustDemo24102642410264rustDemoValue: 42
122rustDemo24102642410264rustDemoGot None
123rustDemo24102642410264rustDemono_param
124rustDemo24102642410264rustDemomut_binding: 6
125rustDemo24102642410264rustDemoref_param: 20
126rustDemo24102642410264rustDemomut_ref_param: 10
127rustDemo24102642410264rustDemotuple_param: 3 + 4 = 7
128rustDemo24102642410264rustDemoslice_param: first=1, second=2
129rustDemo24102642410264rustDemowildcard_param
130rustDemo24102642410264rustDemoResult from closure: 42
131rustDemo24102642410264rustDemoResult from if-else: Hello
132rustDemo24102642410264rustDemoResult from match: Other
133rustDemo24102642410264rustDemoResult from loop: 5
134rustDemo24102642410264rustDemoResult from block: 30
135rustDemo24102642410264rustDemoInside inner_function
136rustDemo24102642410264rustDemoInside inner_inner_function
137rustDemo24102642410264rustDemoInside closure
138rustDemo24102642410264rustDemoInside inner_function_in_closure
139rustDemo24102642410264rustDemoresult3: 100
140rustDemo24102642410264rustDemoString: Hello, world!
141rustDemo24102642410264rustDemoInteger: 42
142rustDemo24102642410264rustDemoNot equal: 3 vs 7
143rustDemo24102642410264rustDemoA: false
144rustDemo24102642410264rustDemoVariant1(42)
145rustDemo24102642410264rustDemo42
146rustDemo24102642410264rustDemoMyTuple(42, true, [18, 52, 86, 120])
147rustDemo24102642410264rustDemomy_struct is a struct: true
148rustDemo24102642410264rustDemoAt 50 0x55d1db858e29ower
149rustDemo24102642410264rustDemoLength of 'Hello, Rust!' is 12
150rustDemo24102642410264rustDemoSum of 5 and 10 is 15
151rustDemo24102642410264rustDemoThe value is: 42
152rustDemo24102642410283rustDemoThread 0 incremented counter to 1
153rustDemo24102642410284rustDemoThread 1 incremented counter to 2
154rustDemo24102642410285rustDemoThread 2 incremented counter to 3
155rustDemo24102642410286rustDemoThread 3 incremented counter to 4
156rustDemo24102642410287rustDemoThread 4 incremented counter to 5
157rustDemo24102642410288rustDemoThread 5 incremented counter to 6
158rustDemo24102642410289rustDemoThread 6 incremented counter to 7
159rustDemo24102642410290rustDemoThread 7 incremented counter to 8
160rustDemo24102642410291rustDemoThread 8 incremented counter to 9
161rustDemo24102642410292rustDemoThread 9 incremented counter to 10
162rustDemo24102642410264rustDemoFinal counter value: 10
163rustDemo24102642410264rustDemo=== Rust Advanced Function Features Demo ===
164rustDemo24102642410264rustDemo1. Diverging Functions Demo:
165rustDemo24102642410264rustDemoNote: Diverging functions never return normally, so we only show their definitions
166rustDemo24102642410264rustDemo- panic_with_message: Can accept any Display type and panic
167rustDemo24102642410264rustDemo- run_infinite_server: Simulates a server that runs forever
168rustDemo24102642410264rustDemo- handle_fatal_error: Handles fatal errors and exits the program
169rustDemo24102642410264rustDemo- Panic handling result: Ok("Normal execution")
170rustDemo24102642410264rustDemo2. Async Functions Demo:
171rustDemo24102642410264rustDemo- Async calculation: 5 + 3 = 8
172rustDemo24102642410264rustDemoFetching data for user 123
173rustDemo24102642410264rustDemo- Fetched: User data for ID: 123
174rustDemo24102642410264rustDemo- Async processed: Number: 42
175rustDemo24102642410264rustDemo3. Generic Returns Demo:
176rustDemo24102642410264rustDemo- Squares: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
177rustDemo24102642410264rustDemo- Display value: Hello, World!
178rustDemo24102642410264rustDemo- Doubled collection: [1, 2, 3, 1, 2, 3]
179rustDemo24102642410264rustDemo- Debug display: Wrapped: Hello (Debug: "Wrapped: Hello")
180rustDemo24102642410264rustDemo- Multiplier result: 4 * 3 = 12
181rustDemo24102642410264rustDemo- Range iterator: [0, 1, 2, 3, 4]
182rustDemo24102642410264rustDemo- Vec iterator: [1, 3, 5, 7, 9]
183rustDemo24102642410264rustDemo
=== Demo Completed :) ===
END 0 0 0 00
Project:rs-demo
Update:20250906
Commit:bdbabb8
Source Code:Main
System:MySystemD
Kernel:Linux5.10.211
Cpu:Intel:Corei7-7700K
Machine:AwesomeMachine