I've always used the following design in my applications:

struct App {
    vector<View> views;
    View* current_view;

current_view is a mutable reference, by modifying it I modify the original array:

app.current_view = &app.views[0];
app.current_view->title = "hello";

After I started learning Rust I found out that this design is simply impossible:


If we create a mutable reference to a vector element, we won't be able to modify the original vector.

An obvious solution is to use indexing:

struct App {
    vector<View> views;
    int current_view_idx;

app.views[app.current_view_idx].title = "hello";

This way it's much easier to handle memory, but the code is more verbose.

Is this a good solution? Is there a better way?


closed as too broad by Doc Brown, Robert Harvey Sep 10 at 18:03

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    The problem with your initial design is, when the vector grows in size and reallocates the required memory internally, the pointer becomes invalid (sometimes, and it not transparent when, which makes this pretty error prone). An index, however, stays valid (at least as long as as vector does not shrink). It is IMHO the most simple solution to the stated problem, and good enough for many real world situations. Asking if there is a "better" way make no sense without context, there are surely situations where an index alone does not fulfill specific requirements. – Doc Brown Sep 10 at 16:03
  • @DocBrown good point, somehow I never faced problems with the relocation. – Alex Sep 10 at 16:06
  • 1
    "but the code is more verbose" Isn't this the reason we have objects? – JimmyJames Sep 10 at 16:18

Browse other questions tagged or ask your own question.