I can cast between types by using either from or as:
i64::from(42i32);
42i32 as i64;
What is the difference between those?
as can only be used in a small, fixed set of transformations. The reference documents as:
ascan be used to explicitly perform coercions, as well as the following additional casts. Here*Tmeans either*const Tor*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 * or
TandVare compatible unsized types, e.g., both slices, both the same trait object.** only for closures that do not capture (close over) any local variables
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(name: impl Into<String>) { /* ... */ }). This is not possible with as (although see AsPrimitive from the num crate).
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With