I am new to rust and cannot understand the issue below. I am trying to store the Trait of Animals in the vector.
My implementation is as below.
mod TestAnimal {
use crate::stack;
pub trait Animal {
fn diagnose(&self) -> Result<(), stack::service::ServiceError>;
}
pub struct Hospital {
animals: Vec<Box<dyn Animal>>,
}
static mut HOSPITAL: Hospital = Hospital { animals: Vec::new() };
impl Hospital {
pub fn add_animal(&mut self, animal: Box<dyn Animal>) {
self.animals.push(animal);
}
}
pub fn get_hospital() -> &'static Hospital {
unsafe {
return &HOSPITAL;
}
}
}
#[test]
fn test_hospital() {
pub struct Cat;
impl TestAnimal::Animal for Cat {
fn diagnose(&self) -> Result<(), stack::service::ServiceError> {
return Ok(());
}
}
TestAnimal::get_hospital().add_animal(Box::new(Cat {}));
}
The issue I am facing is as below.
error[E0596]: cannot borrow data in a `&` reference as mutable
--> src/main.rs:45:5
|
45 | TestAnimal::get_hospital().add_animal(Box::new(Cat {}));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable