728x90
use std::ops::{Deref, DerefMut};
struct HoldsANumber(u8);
impl Deref for HoldsANumber<u8> {
type Target = u8;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for HoldsANumber {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
fn main() {
let my_number = HoldsANumber(20);
println!("{}", my_number.checked_add(10).unwrap() + 20);
}
use std::ops::Deref;
struct Character {
name: String,
strength: u8,
dexterity: u8,
health: u8,
intelligence: u8,
wisdom: u8,
charm: u8,
hit_points: u8,
alignment: Alignment,
}
impl Character {
fn new(
name: String,
strength: u8,
dexterity: u8,
health: u8,
intelligence: u8,
wisdom: u8,
charm: u8,
hit_points: u8,
alignment: Alignment,
) -> Self {
Self {
name,
strength,
dexterity,
health,
intelligence,
wisdom,
charm,
hit_points,
alignment,
}
}
}
enum Alignment {
Good,
Neutral,
Evil,
}
impl Deref for Character {
type target = i8;
fn deref(&self) -> &Self::Target {
&self.hit_points
}
}
fn main() {
let billy = Character::new("Billy".to_string(), 9, 8, 7, 10, 19, 19, 5, Alignment::Good)
let brandy = Character::new("Brandy".to_string(), 9, 8, 7, 10, 19, 19, 5, Alignment::Good)
println!("Now Billy has {} hit points", billy.checked_sub(10).unwrap());
let mut hit_points_vec = vec![];
hit_points_vec.push(*billy);
hit_points_vec.push(*brandy);
println!("All our hit points are: {hit_points_vec:?}");
}
728x90
'Rust' 카테고리의 다른 글
[Rust lang] 95. builder pattern (0) | 2023.03.30 |
---|---|
[Rust lang] 94. add trait (0) | 2023.03.30 |
[Rust lang] 92. attribute part (0) | 2023.03.30 |
[Rust lang] 91. about impl trait (0) | 2023.03.30 |
[Rust lang] 90. fn mut fnonce (0) | 2023.03.30 |
댓글