classes
This commit is contained in:
27
rust/classes/src/car.rs
Normal file
27
rust/classes/src/car.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Define the trait Information that will contain the function print_info()
|
||||
*/
|
||||
pub trait Information {
|
||||
// define the function, &self is an argument that will be autofilled
|
||||
// when running the function and it will reference the current object
|
||||
fn print_info(&self);
|
||||
}
|
||||
|
||||
/*
|
||||
* Define the struct Car, which will hold all the necessary information
|
||||
*/
|
||||
pub struct Car {
|
||||
pub manufacturer: String,
|
||||
pub model: String
|
||||
}
|
||||
|
||||
/*
|
||||
* Implementing the trait Information for the struct Car
|
||||
*/
|
||||
impl Information for Car {
|
||||
fn print_info(&self) {
|
||||
println!("Car Information:");
|
||||
println!("- manufacturer: {}", self.manufacturer);
|
||||
println!("- model: {}", self.model);
|
||||
}
|
||||
}
|
23
rust/classes/src/main.rs
Normal file
23
rust/classes/src/main.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
mod car;
|
||||
use car::Information;
|
||||
|
||||
fn main() {
|
||||
// create a new car and store it in the variable 'a'
|
||||
// rust also doesn't use the 'new' keyword
|
||||
// all attributes have to be defined upon creation of the object
|
||||
let a = car::Car {
|
||||
// set some data for that car
|
||||
manufacturer: "Benz".to_string(),
|
||||
model: "Velo".to_string()
|
||||
};
|
||||
|
||||
// do the same for a second car
|
||||
let b = car::Car {
|
||||
manufacturer: "Ford".to_string(),
|
||||
model: "Model T".to_string()
|
||||
};
|
||||
|
||||
// use a function of the car class to print out the information
|
||||
a.print_info();
|
||||
b.print_info();
|
||||
}
|
Reference in New Issue
Block a user