【发布时间】:2018-02-14 20:04:09
【问题描述】:
我可以使用from 或as 在类型之间进行转换:
i64::from(42i32);
42i32 as i64;
它们之间有什么区别?
【问题讨论】:
我可以使用from 或as 在类型之间进行转换:
i64::from(42i32);
42i32 as i64;
它们之间有什么区别?
【问题讨论】:
as 只能用于一小部分固定的转换。 The reference documents as:
as可用于显式执行coercions,如 以及以下附加演员表。这里*T表示*const T或*mut T.
Type of eUCast performed by e as UInteger or Float type Integer or Float type Numeric cast C-like enum Integer type Enum cast boolorcharInteger type Primitive to integer cast u8charu8tocharcast*T*VwhereV: Sized*Pointer to pointer cast *TwhereT: SizedNumeric type Pointer to address cast Integer type *VwhereV: SizedAddress to pointer cast &[T; n]*const TArray to pointer cast Function item Function pointer Function item to function pointer cast Function item *VwhereV: SizedFunction item to pointer cast Function item Integer Function item to address cast Function pointer *VwhereV: SizedFunction pointer to pointer cast Function pointer Integer Function pointer to address cast Closure ** Function pointer Closure to function pointer cast * 或
T和V是兼容的无大小类型,例如,两个切片,两个 相同的特征对象。** 仅适用于不捕获(关闭)任何局部变量的闭包
因为as 是编译器已知的并且只对某些转换有效,所以它可以进行某些类型的更复杂的转换。
From is a trait,这意味着任何程序员都可以为自己的类型实现它,因此可以应用于更多的情况。它与Into 配对。 TryFrom 和 TryInto 自 Rust 1.34 以来一直稳定。
因为它是一个特征,所以它可以在通用上下文中使用 (fn foo(name: impl Into<String>) { /* ... */ })。 as 无法做到这一点(尽管请参阅 num crate 中的 AsPrimitive)。
在数值类型之间进行转换时,需要注意的一点是 From 仅适用于无损转换(例如,您可以使用 From 从 i32 转换为 i64,但是不是相反),而as 适用于无损和有损转换(如果转换是有损的,它会截断)。因此,如果您想确保不会意外执行有损转换,您可能更喜欢使用From::from 而不是as。
另见:
【讨论】: