我可以使用from
或as
在类型之间进行转换:
i64::from(42i32);
42i32 as i64;
那些有什么区别?
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 pointer | *V where V: Sized | Function pointer to pointer cast | | Function pointer | Integer | Function pointer to address cast |
†或
T
和V
是兼容的未定义类型,例如两个切片,两者都是相同的特征对象。
因为as
是编译器已知的并且仅对某些转换有效,所以它可以执行某些类型的更复杂的转换。
From
is a trait,这意味着任何程序员都可以为自己的类型实现它,因此它可以在更多情况下应用。它与Into
配对。自Rust 1.34以来,TryFrom
和TryInto
一直保持稳定。
因为它是一个特征,它可以在通用上下文中使用(fn foo<S: Into<String>(name: S) { /* ... */}
)。这与as
无法实现。
在数值类型之间进行转换时,有一点需要注意的是From
仅用于无损转换(例如,您可以使用i32
从i64
转换为From
,但不是相反),而as
适用于无损转换和有损转换(如果转换是有损的,它会截断)。因此,如果您想确保不会意外地执行有损转换,您可能更喜欢使用From::from
而不是as
。
也可以看看: