Mutate type of generic variable in Rust

Viewed 782

I know that you can't mutate the type of a variable. So coming from other programming languages where following would work:

struct Point<T> {
    x: T,
    y: T,
}

fn main() {
    let mut p = Point { x: 1, y: 1 }; // p is type of Point<u8> now
    p = Point { x: 1.0, y: 1.0 }; // p should be type of Point<float> now
}

My use case for this would, that you assign a default value to variable and i specific case you change the value. But both are e.g. of the generic type Point<T> and the rest of the code just works with this generic type and not a specific one.

What is the best practice in Rust to achieve this kind of workflow?

EDIT:

A better example to understand what i want to accomplish is maybe following: DateTime<Tz> is given by the crate chrono.


fn main() {
   let is_utc = ....;

   let mut datetime = Local::now(); // datetime is now of type DateType<Local>

   if is_utc {
       datetime = Utc::now(); // datetime is now of type DateType<Utc>
   }

   format(datetime);
}


fn format<Tz: TimeZone>(datetime: DateTime<Tz>) where Tz::Offset : fmt::Display {
    // here is someother code to justify this extra function :)
    datetime.format("%a %b %e %k:%M:%S %Z %Y");
}

So the function format does not are what Tz is except it should be of type TimeZone.

1 Answers

You can set your multi variable type in enum,

enum Num {
    int(i32),
    float(f64)
}

fn main() {
    let mut p = Point { x: Num::int(1), y: Num::int(1) };
    p = Point { x: Num::float(1.0), y: Num::float(1.0) };
}
Related