ADVERTISEMENT
ADVERTISEMENT

Rust program to create a generic structure

Rust | Generics Example: Write a program to create a generic structure.
Submitted by Nidhi, on November 23, 2021

Problem Solution:

In this program, we will create a generic structure. It can store any type of data. Then we will create objects of structure with different types and print results.

Program/Source Code:

The source code to create a generic structure is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to create a generic structure

struct MyStruct<T> {
   val:T,
}

fn main() {
   let num:MyStruct<i32> = MyStruct{val:101};
   println!("Value: {} ",num.val);
   
   let msg:MyStruct<String> = MyStruct{val:"Hello World".to_string()};
   println!("Value: {} ",msg.val);
}

Output:

Value: 101 
Value: Hello World

Explanation:

In the above program, we created a generic structure MyStruct which is given below,

struct MyStruct<T> {
   val:T,
}

In the main() function, we created the objects of structure MyStruct with different data types and printed the result.

Rust Generics Programs »



ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

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.