Q:

Rust program to create a generic structure

belongs to collection: Rust Generics Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust program to declare and implement a trait... >>
<< Rust program to calculate the subtract a number fr...