Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

casting

rust

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

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

What is the difference between those?

like image 567
John Doe Avatar asked Feb 14 '18 20:02

John Doe


1 Answers

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 item Function pointer Function item to function pointer cast
Function item *V where V: Sized Function item to pointer cast
Function item Integer Function item to address cast
Function pointer *V where V: Sized Function pointer to pointer cast
Function pointer Integer Function pointer to address cast
Closure ** Function pointer Closure to function pointer cast

* or T and V 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:

  • When should I implement std::convert::From vs std::convert::Into?
like image 85
Shepmaster Avatar answered Oct 16 '22 05:10

Shepmaster