Rust program to create a simple structure

Rust | Structure Example: Write a program to create a simple structure.
Last Updated : October 27, 2021

Problem Statement

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 »



Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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