Q:

Rust program to create a Static method in the structure

belongs to collection: Rust Structures Programs

0

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.

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 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 num1num2. 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.

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

total answers (1)

<< Rust program to define a method in a struct...