home ~ projects ~ socials

Update Values In A Rust Struct From Another Method

This is a work in progress while I try to figure out how to do this:

#[derive(Debug)]
pub struct Widget {
    items: Vec<Item>,
}

#[derive(Clone, Debug)]
pub struct Item {
    k: Option<usize>,
    v: Option<String>,
}

impl Widget {
    pub fn update_items(&mut self) {
        let mut current_value = 0;
        for x in 0..self.items.len() {
            if self.items[x].k.is_some() {
                continue;
            };
            let target = self.items[x].v.clone();
            self.items
                .iter_mut()
                .filter(|i| i.v == target)
                .for_each(|i| {
                    i.k = Some(current_value);
                });
            current_value += 1;
        }
    }
}

fn main() {
    let mut w = Widget {
        items: vec![
            Item {
                k: None,
                v: Some("bravo".to_string()),
            },
            Item {
                k: None,
                v: Some("alfa".to_string()),
            },
            Item {
                k: None,
                v: Some("alfa".to_string()),
            },
            Item {
                k: None,
                v: Some("bravo".to_string()),
            },
            Item {
                k: None,
                v: Some("charlie".to_string()),
            },
        ],
    };
    w.update_items();
    dbg!(w);
}
Output:
[_active_nvim_run:57:5] w = Widget {
    items: [
        Item {
            k: Some(
                0,
            ),
            v: Some(
                "bravo",
            ),
        },
        Item {
            k: Some(
                1,
            ),
            v: Some(
                "alfa",
            ),
        },
        Item {
            k: Some(
                1,
            ),
            v: Some(
                "alfa",
            ),
        },
        Item {
            k: Some(
                0,
            ),
            v: Some(
                "bravo",
            ),
        },
        Item {
            k: Some(
                2,
            ),
            v: Some(
                "charlie",
            ),
        },
    ],
}
-- end of line --