Rust program to declare and implement a trait

Rust | Generics Example: Write a program to declare and implement a trait.
Last Updated : November 23, 2021

Problem Statement

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!

Load comments ↻


Advertisement
Advertisement
Advertisement

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