What is the difference between From::from and as in Rust?

人走茶凉 提交于 2020-01-23 11:16:30

问题


I can cast between types by using either from or as:

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

What is the difference between those?


回答1:


as can only be used in a small, fixed set of transformations. The reference documents as:

as can be used to explicitly perform coercions, as well as the following additional casts. Here *T means either *const T or *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 |

† or T and V are compatible unsized types, e.g., both slices, both the same trait object.

Because as is known to the compiler and only valid for certain transformations, it can do certain types of more complicated transformations.

From is a trait, which means that any programmer can implement it for their own types and it is thus able to be applied in more situations. It pairs with Into. TryFrom and TryInto have been stable since Rust 1.34.

Because it's a trait, it can be used in a generic context (fn foo<S: Into<String>(name: S) { /* ... */}). This is not possible with as.

When converting between numeric types, one thing to note is that From is only implemented for lossless conversions (e.g. you can convert from i32 to i64 with From, but not the other way around), whereas as works for both lossless and lossy conversions (if the conversion is lossy, it truncates). Thus, if you want to ensure that you don't accidentally perform a lossy conversion, you may prefer using From::from rather than as.

See also:

  • When should I implement std::convert::From vs std::convert::Into?


来源:https://stackoverflow.com/questions/48795329/what-is-the-difference-between-fromfrom-and-as-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!