Rust program to create a simple structure

Rust | Structure Example: Write a program to create a simple structure.
Submitted by Nidhi, on October 27, 2021

Problem Solution:

In this program, we will create a structure with few members. Then we will create and initialize the structure with values.

Program/Source Code:

The source code to create a simple structure is given below. The given program is compiled and executed successfully.

// Rust program to create a simple structure

struct MyStruct {
   num:u32,
   str:String
}

fn main() {

   let obj = MyStruct {
      num:100,
      str:String::from("Hello World")
   };
   
   println!("Structure elements");
   println!("  Num: {}",obj.num);
   println!("  Str: {}",obj.str);
}

Output:

Structure elements
  Num: 100
  Str: Hello World

Explanation:

In the above program, we created a structure MyStruct and function main(). The MyStruct structure contains two members num and str.

In the main() function, we created and initialized the structure. Then we access structure elements using the "." operator and printed them.

Rust Structures Programs »





Comments and Discussions!

Load comments ↻





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