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 »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.