[Feature Request] Allow initialization of struct fields based on previously initialized fields

Basically, this:

State {
    timers: vec![15, 30, 60, 120],
    selected_timer: 1,
    countdown: timers[selected_timer],

As far as I know, the only way to do this now is to create the variables outside the struct initialization and then move them inside as fields.

I am aware the struct doesn't exist until its initialization, so you can't really call some of its fields initialized and others not, but I feel there should be some sort of syntactic sugar to allow such initializations.

Does this pattern come up a lot? Can you come up with other motivating examples, preferably from real world code?

I've ran into this problem several times, but I think it's tolerable, and not worth introducing a new type of syntax.

In current Rust this can be simplified to:

let timers = vec![15, 30, 60, 120];
let selected_timer = 1;

State {
    countdown: timers[selected_timer],

Note that this works for countdown: Copy + 'static. The general form skirts very close to the self-reference situation.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.