Всем привет, учу rust, не
понимаю для чего нужны traits.
приложил простой кусок кода, я хочу сравнить поля 2х структур в методе stronger_than
как мне это сделать ?
pub struct Animal {
pub name: String,
pub age: i32,
pub strength: i32,
}
pub struct Person {
pub name: String,
pub age: i32,
pub strength: i32,
}
trait BaseTrait {
fn init(&self);
fn stronger_than<T>(&self, target: T) -> bool;
}
impl BaseTrait for Person {
fn init(&self) {
println!("Hello, im Person: {}", self.name);
}
fn stronger_than<T>(&self, enemy: T) -> bool {
self.strength > enemy.strength
}
}
impl BaseTrait for Animal {
fn init(&self) {
println!("Hello, im Animal: {}", self.name);
}
fn stronger_than<T>(&self, enemy: T) -> bool {
self.strength > enemy.strength
}
}
fn main() {
let person = Person { name: String::from("John"), age: 25, strength: 12 };
let animal = Animal { name: String::from("Elephant"), age: 5, strength: 360 };
person.init();
animal.init();
person.stronger_than(&animal);
animal.stronger_than(&person);
}
Вот такой код рабочий, без трейтов, но входной тип не динамический
pub struct Animal {
pub name: String,
pub age: i32,
pub strength: i32,
}
pub struct Person {
pub name: String,
pub age: i32,
pub strength: i32,
}
impl Person {
fn init(&self) {
println!("Hello, im Person: {}", self.name);
}
fn stronger_than(&self, enemy: &Animal) -> bool {
let result = self.strength > enemy.strength;
println!("{} is stronger ? : {}", self.name, result);
result
}
}
impl Animal {
fn init(&self) {
println!("Hello, im Animal: {}", self.name);
}
fn stronger_than(&self, enemy: &Person) -> bool {
let result = self.strength > enemy.strength;
println!("{} is stronger ? : {}", self.name, result);
result
}
}
fn main() {
let person = Person { name: String::from("John"), age: 25, strength: 12 };
let animal = Animal { name: String::from("Elephant"), age: 5, strength: 360 };
person.init();
animal.init();
person.stronger_than(&animal);
animal.stronger_than(&person);
}