我可以使用from
或之一在类型之间进行转换as
:
i64::from(42i32);
42i32 as i64;
Run Code Online (Sandbox Code Playgroud)
那些有什么区别?
She*_*ter 10
as
只能用于一组固定的小型转换.参考文件as
:
as
可用于显式执行强制,以及以下额外的强制转换.这*T
意味着*const T
或者*mut T
.Run Code Online (Sandbox Code Playgroud)| 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
是一个特征,这意味着任何程序员都可以为自己的类型实现它,因此它可以在更多情况下应用.它配对Into
.最终,TryFrom
并且TryInto
也将趋于稳定.
因为它是一个特征,所以它可以在泛型上下文中使用(fn foo<S: Into<String>(name: S) { /* ... */}
).这是不可能的as
.
在数字类型之间进行转换时,需要注意的一点是,From
只能实现无损转换(例如,您可以转换i32
为i64
with From
,而不是相反),而as
适用于无损转换和有损转换(如果转换是有损的,它截断).因此,如果您想确保不会意外执行有损转换,您可能更愿意使用From::from
而不是as
.
也可以看看:
归档时间: |
|
查看次数: |
2247 次 |
最近记录: |