【问题标题】:What is the difference between From::from and as in Rust?Rust 中的 From::from 和 as 有什么区别?
【发布时间】:2018-02-14 20:04:09
【问题描述】:

我可以使用fromas 在类型之间进行转换:

i64::from(42i32);
42i32 as i64;

它们之间有什么区别?

【问题讨论】:

    标签: casting rust


    【解决方案1】:

    as 只能用于一小部分固定的转换。 The reference documents as:

    as 可用于显式执行coercions,如 以及以下附加演员表。这里*T 表示*const T*mut T.

    Type of e U Cast performed by e as U
    Integer or Float type Integer or Float type Numeric cast
    C-like enum Integer type Enum cast
    bool or char Integer type Primitive to integer cast
    u8 char u8 to char cast
    *T *V where V: Sized * Pointer to pointer cast
    *T where T: Sized Numeric type Pointer to address cast
    Integer type *V where V: Sized Address to pointer cast
    &[T; n] *const T Array to pointer cast
    Function item Function pointer Function item to function pointer cast
    Function item *V where V: Sized Function item to pointer cast
    Function item Integer Function item to address cast
    Function pointer *V where V: Sized Function pointer to pointer cast
    Function pointer Integer Function pointer to address cast
    Closure ** Function pointer Closure to function pointer cast

    * 或 TV 是兼容的无大小类型,例如,两个切片,两个 相同的特征对象。

    ** 仅适用于不捕获(关闭)任何局部变量的闭包

    因为as 是编译器已知的并且只对某些转换有效,所以它可以进行某些类型的更复杂的转换。

    From is a trait,这意味着任何程序员都可以为自己的类型实现它,因此可以应用于更多的情况。它与Into 配对。 TryFromTryInto 自 Rust 1.34 以来一直稳定。

    因为它是一个特征,所以它可以在通用上下文中使用 (fn foo(name: impl Into<String>) { /* ... */ })。 as 无法做到这一点(尽管请参阅 num crate 中的 AsPrimitive)。

    在数值类型之间进行转换时,需要注意的一点是 From 仅适用于无损转换(例如,您可以使用 Fromi32 转换为 i64,但是不是相反),而as 适用于无损和有损转换(如果转换是有损的,它会截断)。因此,如果您想确保不会意外执行有损转换,您可能更喜欢使用From::from 而不是as

    另见:

    【讨论】:

      猜你喜欢
      • 2019-06-07
      • 2019-07-02
      • 2018-09-21
      • 1970-01-01
      • 2016-08-28
      • 2011-05-21
      • 1970-01-01
      • 2018-11-29
      • 2020-07-23
      相关资源
      最近更新 更多