我知道你无法改变变量的类型。 因此,对于其他编程语言中可行的以下操作:
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
}
我的使用情况是,您为变量分配默认值,而在某些特定情况下,更改该值。 但两者都是泛型类型
Point<T>
的示例,其余代码仅使用此通用类型而不是特定类型。在Rust中实现此类工作流程的最佳做法是什么?更好的示例可能如下:chrono
提供了DateTime<Tz>
。
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");
}
因此,函数
format
并不关心Tz
是什么,除了它应该是TimeZone
类型。
Vec
内部值的类型,对吧?)。我看到两种可能性。使用Default::default
并添加要求T: Default
,然后你可以写:let mut p: Point<f32> = Point::Default
。 - hellowPoint<int> p = new Point<int>(1, 2);
后,你不能再写p = new Point<float>(1f, 2f);
。如果该类是可变的,你甚至不能编写p.X = 2.1f;
,因为p
是一个包含整数的结构体。将泛型类视为具体类的模板,当你指定参数时,它们就被固定下来了。 - vgru