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
:
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
orchar
Integer type Primitive to integer cast u8
char
u8
tochar
cast*T
*V
whereV: Sized
*Pointer to pointer cast *T
whereT: Sized
Numeric type Pointer to address cast Integer type *V
whereV: Sized
Address to pointer cast &[T; n]
*const T
Array to pointer cast Function item Function pointer Function item to function pointer cast Function item *V
whereV: Sized
Function item to pointer cast Function item Integer Function item to address cast Function pointer *V
whereV: Sized
Function pointer to pointer cast Function pointer Integer Function pointer to address cast Closure ** Function pointer Closure to function pointer cast * or
T
andV
are 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