16.1 Introduction to Type Conversions
Working with multiple data types is common in most programs. In C, the compiler may perform implicit conversions (e.g., from int
to double
in arithmetic expressions), often without you noticing. Rust, by contrast, enforces explicit conversions to ensure clarity and safety.
16.1.1 Rust’s Philosophy: Safety and Explicitness
Rust’s compiler does not allow the silent type conversions seen in C. Instead, Rust expects you to explicitly indicate any type changes—through as
, the From
/Into
traits, or the TryFrom
/TryInto
traits, for instance. This design helps developers avoid common C pitfalls, such as accidental truncations, sign mismatches, or unexpected precision loss.
Rust’s philosophy for conversions can be summarized as follows:
- All Conversions Must Be Explicit
If the type must change, you must write code that clearly expresses that intent. - Handle Potential Failures
Conversions that might fail—such as parsing an invalid string or casting a large integer into a smaller type—return aResult
that you must handle. This prevents silent errors.
16.1.2 Types of Conversions in Rust
Rust groups conversions into two main categories:
-
Safe (Infallible) Conversions
Implemented via theFrom
andInto
traits. These conversions cannot fail. One common example is converting au8
to au16
—this always works without loss of information. -
Fallible Conversions
Implemented via theTryFrom
andTryInto
traits, which return aResult<T, E>
. This is used for conversions that might fail, such as parsing a string into an integer that may not fit into the target type.