Q:

Rust program to declare and implement a trait

belongs to collection: Rust Generics Programs

0

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

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

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

total answers (1)

<< Rust program to create a generic structure...