Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Vector iterate and update
hi,
I am a new beginner in Rust. I have a list of structs in a vector, which I am trying to iterate, filter and update matching values.
From docs, my understanding is that when we iterate and filter a vector, the result is a new/copy of the vector, not the original one.
How to approach this, the option I see while searching online is to use afor
loop with an index.
for i in 0...vec.len(){}
code i am trying to do
ex :
pub struct Item {
pub name: String,
pub sell_in: i32,
pub quality: i32,
}
let items = vec![
Item::new("+5 Dexterity Vest", 10, 20),
Item::new("Aged Brie", 2, 0),
Item::new("Elixir of the Mongoose", 5, 7),
Item::new("Sulfuras, Hand of Ragnaros", 0, 80),
Item::new("Sulfuras, Hand of Ragnaros", -1, 80),
Item::new("Backstage passes to a TAFKAL80ETC concert", 15, 20),
Item::new("Backstage passes to a TAFKAL80ETC concert", 10, 49),
Item::new("Backstage passes to a TAFKAL80ETC concert", 5, 49),
Item::new("Conjured Mana Cake", 3, 6),
];
pub fn update_quality(&mut self) {
let back_stage_iter: Vec<&Item> = self
.items
.iter()
.filter(|&x| {
x.name == "Backstage passes to a TAFKAL80ETC concert"
&& x.sell_in < 11
&& x.quality < 50
})
.collect();
for v in back_stage_iter {
*v.quality = *v.quality + 1;
}
In the above *v.quality=*v.quality+1
am getting me can not assign a value to a reference.
2 posts - 2 participants
🏷️ Rust_feed