Rust program to create a Static method in the structure

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

Problem Solution:

In this program, we will create a structure Sample. Then we will define an instance method and a static method in the structure by implementing the structure using the impl keyword.

Program/Source Code:

The source code to create a Static method in the structure is given below. The given program is compiled and executed successfully.

// Rust program to create a Static method 
// in the structure

struct Sample {
   num1: i32,
   num2: i32,
}

impl Sample {
   //Static method
   fn createStruct(n1: i32, n2: i32) -> Sample {
      Sample { num1: n1, num2: n2 }
   }
 
   fn printStruct(&self){
      println!("Num1 = {}",self.num1);
      println!("Num2 = {}",self.num2);
   }
}

fn main(){
   let s = Sample::createStruct(10,20);
   s.printStruct();
}

Output:

Num1 = 10
Num2 = 20

Explanation:

In the above program, we created a structure Sample and function main(). The Sample structure contains members num1, num2. And, we implemented an instance and a static method inside the structure.

In the main() function, we created the object of Sample structure using the static method createStruct(). Then we printed the members of the structure.

Rust Structures Programs »






Comments and Discussions!

Load comments ↻






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