ADVERTISEMENT
ADVERTISEMENT

Rust program to demonstrate the 'from' trait

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

Problem Solution:

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

Program/Source Code:

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

// 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); 
}

Output:

hello world, Type: &str
hello world, Type: alloc::string::String

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.

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.