ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.