From :: from和Rust之间有什么区别?

Joh*_*Doe 3 casting rust

我可以使用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.

| 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 |
Run Code Online (Sandbox Code Playgroud)

†或TV兼容未施胶的类型,例如,两个层,两个相同的性状的对象.

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

From是一个特征,这意味着任何程序员都可以为自己的类型实现它,因此它可以在更多情况下应用.它配对Into.最终,TryFrom并且TryInto也将趋于稳定.

因为它是一个特征,所以它可以在泛型上下文中使用(fn foo<S: Into<String>(name: S) { /* ... */}).这是不可能的as.

在数字类型之间进行转换时,需要注意的一点是,From只能实现无损转换(例如,您可以转换i32i64with From,而不是相反),而as适用于无损转换和有损转换(如果转换是有损的,它截断).因此,如果您想确保不会意外执行有损转换,您可能更愿意使用From::from而不是as.

也可以看看: