Rust program to demonstrate the 'from' trait


Program to demonstrate the 'from' trait

Rust Programming Language


Program to demonstrate the 'from' trait


Problem


In this program, we will demonstrate the "from" trait. The "from" trait is used to create a variable from another type of variable.


Input


// Rust program to demonstrate the "from" trait

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

fn main() 
{
    let strVar = "hello world";
    let stringVar = String::from(strVar);

    print!("{}, Type: ",strVar);
    TypeOf(&strVar); 
    
    print!("{}, Type: ",stringVar);
    TypeOf(&stringVar); 
}{codeBox}


Output


hello world, Type: &str
hello world, Type: alloc::string::String{codeBox}


Explanation


Here, we created a variable strVar of &str type. Then we created another variable stringVar using the "from" trait using the existing variable strVar. After that, we printed the value of variables and their data type.


Post a Comment