In the following code, I want automatically initialize my array:
struct ColorQueue {
queue: String,
color: String,
}
impl ColorQueue {
pub fn new(queue: &str) -> Self {
Self {
queue: String::from(queue),
color: "".to_string(),
}
}
fn name_colors(&self) {
let colorqueue = [
ColorQueue {
queue: "amig".to_string(),
color: "HRED".to_string(),
},
ColorQueue {
queue: "micmac".to_string(),
color: "GRN".to_string(),
},
ColorQueue {
queue: "ssfa".to_string(),
color: "YEL".to_string(),
},
ColorQueue {
queue: "chrody".to_string(),
color: "BLU".to_string(),
},
ColorQueue {
queue: "ngs".to_string(),
color: "MAG".to_string(),
},
ColorQueue {
queue: "emc2".to_string(),
color: "CYN".to_string(),
},
ColorQueue {
queue: "cryoem".to_string(),
color: "WHT".to_string(),
},
ColorQueue {
queue: "common".to_string(),
color: "BWHT".to_string(),
},
ColorQueue {
queue: "lowprio".to_string(),
color: "RED".to_string(),
},
ColorQueue {
queue: "bim".to_string(),
color: "BCYN".to_string(),
},
ColorQueue {
queue: "runxx".to_string(),
color: "BBLU".to_string(),
},
];
}
pub fn set_queue_name(&mut self, queue: String) {
self.queue = queue;
}
pub fn get_color(&self) -> &String {
for item in 1..self.colorqueue.len() {
if self.queue == self.colorqueue[item].queue {
return &self.colorqueue[item].color;
}
}
}
pub fn get_queue_name(&self) -> &String {
return &self.queue;
}
}
fn main() {
let mut cqueue = ColorQueue::new(&"amig");
ColorQueue::set_queue_name("amig".to_string());
println!("{}", cqueue.get_queue_name());
cqueue.set_queue_name("ngs".to_string());
println!("{}", cqueue.get_queue_name())
}
For now I can assign a queue. What I want is a function get_color(queue)
that returns the color field, depending on queue name.
This should return "MAG"
:
cqueue.set_queue_name("ngs".to_string());
cqueue.get_color();
But I must initialize my array in the object.