ADVERTISEMENT
ADVERTISEMENT

Rust program to declare and implement a trait

Rust | Generics Example: Write a program to declare and implement a trait.
Submitted by Nidhi, on November 23, 2021

Problem Solution:

In this program, we will create a structure and implement a trait to print student information.

Program/Source Code:

The source code to declare and implement a trait is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to declare and implement a trait

struct Student {
   id:u32,
   name:&'static str,
   fee:u32
   
}

//declare a trait
trait PrintStudent {
   fn print(&self);
}

//implement the trait
impl PrintStudent for Student {
   fn print(&self){
      println!("Student id   : {}",self.id  );
      println!("Student name : {}",self.name);
      println!("Student fee  : {}",self.fee );
   }
}

fn main()
{
   let stu = Student {
      id:1001,
      name:"Rahul",
      fee:5000
   };
   stu.print();
}

Output:

Student id   : 1001
Student name : Rahul
Student fee  : 5000

Explanation:

In the above program, we created a structure Student which is given below,

struct Student {
   id:u32,
   name:&'static str,
   fee:u32
}

After that, we implemented a trait to print student information.

In the main() function, we created the object of the structure Student and initialized it with student information. After that, we printed the student information.

Rust Generics Programs »



ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

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.