Struct with reference to its own vector item

struct Test<'a> {
    strings: Vec<String>,
    current_string: &'a String
}

impl<'a>  Test<'a> {
    pub fn set_current_string(&'a mut self, idx: usize) {
        self.current_string = &self.vector[idx];
    }
}

Suppose I have a struct that holds (and owns) a Vec<Strings>, and also keeps a reference to one of the String within the vector.

Is there a way to initialize it as it is? Or am I forced to use an Option to wrap current_string and initialize it always with None?

Eg, this does not work because the vector gets moved

  let vector = vec!["test".to_string(), "test2".to_string()];
  let mut test = Test{
      vector,
      current_string: &vector[0]
  };

The signature of set_current_string means that self will be permanently borrowed, and unusable after that.

Self-referential struct are not possible in safe rust.

As an illustration.... consider changing the current_string into an index for looking up in the vec. What should happen if the caller sets the current string index, and then the vec is modified?

References in rust have strong guarantees about their validity, which is why the compiler doesn't allow this pattern. Using an index, you need to consider the "vec changed" case, and figure out what that means for your use case.

2 Likes

On the practical level,

  • use an index instead of a &String, or
  • just hold a &str that isn't part of struct Test, or
  • look for more targeted solutions like a string interner or such
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.