This commit is contained in:
2020-05-03 15:12:03 +02:00
parent 8143d66e49
commit f5c60a26f2
19 changed files with 340 additions and 9 deletions

27
rust/classes/src/car.rs Normal file
View 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
View 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();
}