【问题标题】:Mutate type of generic variable in RustRust 中泛型变量的变异类型
【发布时间】:2019-10-10 07:47:33
【问题描述】:

我知道你不能改变变量的类型。 因此,来自其他适用于以下工作的编程语言:

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&lt;T&gt; 的泛型类型,其余代码仅适用于这种泛型类型,而不是特定的类型。

Rust 中实现这种工作流程的最佳实践是什么?

编辑:

了解我想要完成的更好的示例可能如下: DateTime&lt;Tz&gt; 由箱子 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");
}

所以函数format 不是Tz 的功能,只是它应该是TimeZone 类型。

【问题讨论】:

  • 如您所说:您无法更改类型。此外,我不明白你为什么需要从你的评论中得到它。您需要事先知道您期望的类型(您也不能在运行时更改 Vec 中的值类型,对吗?)。我看到了两种可能性。使用Default::default并添加要求T: Default然后你可以写:let mut p: Point&lt;f32&gt; = Point::Default
  • 您可以在弱类型语言中执行此操作,但在支持泛型的强类型语言中,您无法更改泛型参数。例如。如果你在 C# 中写了Point&lt;int&gt; p = new Point&lt;int&gt;(1, 2);,之后你就不能写p = new Point&lt;float&gt;(1f, 2f);。如果类是可变的,你甚至不能写p.X = 2.1f;,因为p 是一个包含整数的结构。将泛型类视为具体类的模板,当您指定一个参数时,这些类是一成不变的。
  • @hellow 这不正是我想要做的。请参阅我编辑的问题。
  • @Groo 是的,我明白这一点。我只想知道如何解决我的问题的最佳实践代码。

标签: variables generics types rust


【解决方案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) };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多