classes
This commit is contained in:
5
rust/classes/Cargo.lock
generated
Normal file
5
rust/classes/Cargo.lock
generated
Normal file
@ -0,0 +1,5 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
[[package]]
|
||||
name = "rust-oop"
|
||||
version = "0.1.0"
|
9
rust/classes/Cargo.toml
Normal file
9
rust/classes/Cargo.toml
Normal file
@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "rust-oop"
|
||||
version = "0.1.0"
|
||||
authors = ["Timo Hocker <t-hocker@web.de>"]
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
11
rust/classes/README.md
Normal file
11
rust/classes/README.md
Normal file
@ -0,0 +1,11 @@
|
||||
# Classes in Rust
|
||||
|
||||
Rust doesn't have classes like Java or other typical c style languages. Instead
|
||||
there are Structs and Traits.
|
||||
|
||||
Structs are responsible for storing data and nothing else. Traits define
|
||||
functions that can be used.
|
||||
|
||||
## Relevant Files
|
||||
|
||||
- [car.rs](./src/car.rs)
|
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