在 Rust 中改变泛型变量的类型

3

我知道你无法改变变量的类型。 因此,对于其他编程语言中可行的以下操作:

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 - hellow
你可以在弱类型语言中这样做,但在支持泛型的强类型语言中,你不能更改泛型参数。例如,在C#中编写Point<int> p = new Point<int>(1, 2);后,你不能再写p = new Point<float>(1f, 2f);。如果该类是可变的,你甚至不能编写p.X = 2.1f;,因为p是一个包含整数的结构体。将泛型类视为具体类的模板,当你指定参数时,它们就被固定下来了。 - vgru
@你好,这不是我想做的事情。请查看我的编辑后的问题。 - kegesch
@Groo 是的,我理解。我只是想知道一个最佳实践代码,如何解决我的问题。 - kegesch
1个回答

1
你可以在 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) };
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接