Best way to model storing an iterator for a vector inside same struct

Viewed 91

Context

I'm a beginner, and, at a high level, what I want to do is store some mutable state (to power a state machine) in a struct with the following constraints

  • Mutating the state doesn't require the entire struct to be mut (since I'd have to update a ton of callsites to be mut + I don't want every field to be mutable)
  • The state is represented as an enum, and can, in the right state, store a way to index into the correct position in a vec that's in the same struct

I came up with two different approaches/examples that seem quite complicated and I want to see if there's a way to simplify. Here's some playgrounds that minimally reproduce what I'm exploring

  1. Using a Cell and a usize
#[derive(Clone, Copy)]
enum S {
    A,
    B(usize),
}

struct Test {
    a: Vec<i32>,
    b: Cell<S>,
}

where usage look like this

println!("{}", t.a[index]);
t.b.set(S::B(index + 1));
  1. Using a RefCell and an iterator
enum S<'a> {
    A,
    B(Iter<'a, i32>),
}

struct Test<'a> {
    a: Vec<i32>,
    b: RefCell<S<'a>>,
}

where usage looks like this

println!("{}", iter.next().unwrap());

Questions

  1. Is there a better way to model this in general vs. what I've tried?
  2. I like approach #2 with the iterator better in theory since it feels cleaner, but I don't like how it introduces explicit lifetime annotations into the struct...in the actual codebase I'm working on, I'd need to update a ton of callsites to add the lifetime annotation and the tiny bit of convenience doesn't seem worth it. Is there some way to do #2 without introducing lifetimes?
0 Answers
Related