What 's happen with borrow checker?
⚓ Rust 📅 2025-10-27 👤 surdeus 👁️ 3// Decorator
type Name<'a> = &'a str;
#[cfg_attr(test, derive(Clone))]
#[derive(PartialEq, PartialOrd,Debug)]
pub enum Role{
Employee,
Customer,
Both,
None
}
pub struct Person<'a>{
name:Name<'a>,
role:Role
}
impl <'a> Person <'a>{
pub fn get_name(&self)->Name<'a>{
self.name
}
pub fn set_name(&mut self,name:&'a str){
self.name = name;
}
pub fn add_role(self:&mut Self){
self.role = match (*self).role {
Role::Employee| Role::None=> Role::Employee,
Role::Customer| Role::Both=> Role::Both,
};
}
}
//
//Decoration1;
pub struct Employee<'a>{
person:&'a Person<'a>
}
impl <'a>Employee<'a> {
pub fn add_role (person:&'a mut Person<'a>)->Self{
person.add_role();
let person:&Person = &*person;
Self{
person
}
}
}
//Decoration2;
pub struct Customer<'a>{
person:&'a Person<'a>
}
impl <'a>Customer<'a> {
pub fn add_role (person:&'a mut Person<'a>)->Self{
person.add_role();
let person= &*person;
Self{
person
}
}
}
#[cfg(test)]
mod decorator_test {
use super::*;
#[test]
fn test_decorator() {
let mut p = Person{
name:"Name",
role:Role::None
};
//decorate to employee
assert_eq!(Role::None,p.role);
let e = Employee::add_role(&mut p);
assert_eq!("Name",e.person.get_name());
assert_eq!(Role::Employee,e.person.role);
// error appear here
let c = Customer::add_role(&mut p);
assert_eq!(Role::Both,c.person.role);
}
#[derive(PartialEq, Eq, PartialOrd, Ord,Debug)]
enum State {
On,
Off
}
impl State {
fn turn_on<'a>(c:&'a mut State) {
*c = State::On;
}
fn turn_off<'a>(c:&'a mut State) {
*c = State::Off;
}
}
#[test]
fn reference_test(){
let mut p = "10";
p = "20";
assert_eq!(p,"20");
let p =&mut "10";
*p = "20";
assert_eq!(*p,"20");
let mut c = State::Off;
State::turn_on(&mut c);
assert_eq!(c,State::On);
State::turn_off(&mut c);
assert_eq!(c,State::Off);
}
}
in the same case
impl State {
fn turn_on<'a>(c:&'a mut State) {
*c = State::On;
}
fn turn_off<'a>(c:&'a mut State) {
*c = State::Off;
}
}
#[test]
fn reference_test(){
let mut p = "10";
p = "20";
assert_eq!(p,"20");
let p =&mut "10";
*p = "20";
assert_eq!(*p,"20");
let mut c = State::Off;
State::turn_on(&mut c);
assert_eq!(c,State::On);
State::turn_off(&mut c);
assert_eq!(c,State::Off);
}
it work well.
playground
5 posts - 3 participants
🏷️ Rust_feed