How to change the data itself via impl function

I wannt the MyData(as below) can change itself by passing a function change_type().


#[derive(Debug)]
enum MyData{
  FLOAT(f64),
  INT(f32)
}

impl MyData{
    fn change_type(&mut self){
        self = match self {
            MyData::FLOAT(x) => self,   //if it's float, remain the same,
            MyData::INT(x) => &mut MyData::FLOAT(x as f64),   //if it's int, then convert it to f64. 
//But it warns: casting &mut f32 as f64 is invalid, how to write the code here ? I tried the AsMut but seem not for here.
        }
    }
}

  fn main(){
    let mut a = MyData::INT(100.0_f32);
    a.change_type();        // I don't wanna this way:    let a = a.change_type .
    
    println!("{:?}", a);    // I wannt :  MyData::FLOAT(100.0), after go through the function change_type()
  }

The problems in this code are all about trying to work with references when you need values. The key is to dereference self (a &mut MyData) when reading and writing it, so that you are matching and constructing a MyData instead of an &mut MyData), and also x is a number, not a reference to a number:

impl MyData {
    fn change_type(&mut self) {
        *self = match *self {
            MyData::FLOAT(x) => MyData::FLOAT(x),
            MyData::INT(x) => MyData::FLOAT(x as f64),
        };
    }
}
2 Likes

Thanks so much.