ADVERTISEMENT
ADVERTISEMENT

Rust program to demonstrate the 'into' trait

Rust Example: Write a program to demonstrate the "into" trait.
Submitted by Nidhi, on November 27, 2021

Problem Solution:

In this program, we will demonstrate the "into" trait, and, convert the variable of i32 type into a complex type structure.

Program/Source Code:

The source code to demonstrate the "into" trait is given below. The given program is compiled and executed successfully.

// Rust program to demonstrate the "into" trait

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

#[derive(Debug)]
struct NumStruct {
    num: i32,
}

impl From<i32> for NumStruct {
    fn from(item: i32) -> Self {
        NumStruct { num: item }
    }
}

fn main() 
{
    let intVar = 5;
    let num: NumStruct = intVar.into();
    
    print!("intVar {:?}, Type: ", intVar);
    TypeOf(&intVar); 
    
    print!("num {:?}, Type: ", num);
    TypeOf(&num); 
}

Output:

intVar 5, Type: i32
num NumStruct { num: 5 }, Type: main::NumStruct

Explanation:

Here, we created  a variable intVar  of i32 type. Then we created another variable num using "into" trait using existing variable intVar. After that, we printed the value of variables and their data type.

Rust Miscellaneous Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.