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.
Vecat runtime as well, can you?). I see two possibilities. UseDefault::defaultand add the requirementT: Defaultand then you can write:let mut p: Point<f32> = Point::DefaultPoint<int> p = new Point<int>(1, 2);in C#, you cannot writep = new Point<float>(1f, 2f);afterwards. If the class was mutable, you couldn't even writep.X = 2.1f;becausepis a struct containing integers. Think of generic classes as templates for concrete classes that are set in stone when you specify a parameter.