How to change deep variables?

I created an example.
I create my_city variable. It stores information about the population of the city.
How can I change only the population value?

struct Amsterdam {
    population:i32,
    timezone:i32,
}

enum City{
    Amsterdam(Amsterdam),
}

enum Country{
    Netherlands(City),
}


fn main(){

  let mut my_city = Country::Netherlands(City::Amsterdam(Amsterdam{
      population:821752,
      timezone:2
  }));
  

  if let Country::Netherlands(City::Amsterdam(Amsterdam {population,..})) = my_city{
     println!("{}",population);
  };

}

Can I change the population inside "if let"?

Now I do it like this:

  let mut my_city = Country::Netherlands(City::Amsterdam(Amsterdam{
      population:821752,
      timezone:2
  }));

my_city = Country::Netherlands(City::Amsterdam(Amsterdam{
      population:900000,
      timezone:2
  }));

  if let Country::Netherlands(City::Amsterdam(Amsterdam {population,..})) = my_city{
     println!("{}",population);
  };

I find this wrong and inconvenient.

I would like like this:

  if let Country::Netherlands(City::Amsterdam(Amsterdam {mut population,..})) = my_city{
     population = 900000;
     println!("{}",population);
  };

help me please

You are so close, try ref mut instead of mut:

struct Amsterdam {
    population: i32,
    timezone: i32,
}

enum City {
    Amsterdam(Amsterdam),
}

enum Country {
    Netherlands(City),
}

fn main() {
    let mut my_city = Country::Netherlands(City::Amsterdam(Amsterdam {
        population: 821752,
        timezone: 2,
    }));

    if let Country::Netherlands(City::Amsterdam(Amsterdam {
        ref mut population, ..
    })) = my_city
    {
        *population = 90000;
    };

    if let Country::Netherlands(City::Amsterdam(Amsterdam { population, .. })) = my_city {
        assert_eq!(population, 90000);
    };
}

Playground.

ref and mut are called binding modes in Rust patterns. You can read more about them in the Reference.

3 Likes

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.