本页尚未翻译,以下为英文原文。
#2.14. Conversions
本页内容
This section defines the syntax that moves a value from one type to another. as is built into the language; .into() and .try_into() are ordinary method calls on standard library traits, whose impls form the standard library's conversion matrix.
cast_expr ::= expr "as" type_expr
into_expr ::= expr "." "into" ("::" "<" type_expr ">")? "(" ")"
try_into ::= expr "." "try_into" ("::" "<" type_expr ">")? "(" ")"
#2.14.1. Three forms
The three forms and what each one runs:
| Form | Shape | Runs |
|---|---|---|
as cast | expr as Type | a built-in cast (no trait) |
.into() call | expr.into() | Target::from (Into::into) |
.try_into() call | expr.try_into::<T>() | Target::try_from (TryInto::try_into) |
There is no Cast trait, and a user type cannot add as pairs. The exact signatures of From / Into and TryFrom / TryInto, and which type pairs implement them, are defined in the standard library's conversion matrix.
#2.14.2. as casts
The first form is the as cast.
expr as Type
as is a keyword; the left side is any expression and the right side is a type expression. The compiler lowers the cast directly; no trait method is called. It is used for conversions that may not preserve the value, such as bit truncation, sign extension and representation changes, and gives the same result as .wrapping_into::<T>() (stdlib 2.11.5).
let x: i32 = 256i32;
let y: u8 = x as u8; // 0
let z: f64 = x as f64; // 256.0
The allowed pairs are a fixed set:
- Any type to itself (a no-op).
- Between any two of the integer types, the floating-point types,
bool,charandc_char. There are two restrictions. The targetbool: onlyboolcasts tobool. The targetchar: onlyu8 as char(andchar as char) is allowed, since a wider value may be a surrogate or lie pastU+10FFFF. Other integer, floating-point,boolandc_char→charcasts are type errors, with the messageonly `u8` can be cast as `char`, not `u32`; use `char::from_u32(n)` (`char | none`) for a wider value. - A payload-less
enumto an integer type, giving its tag or value (2.4.2). - To or from the arbitrary-precision std types
int/float. A cast into one runs the losslessFromimpl, so a pair without one (f64 as int) is an error; a cast out of one runs the target'sWrappingFromimpl.
From a floating-point type to an integer type, as truncates toward zero and saturates: a value past the target's range gives its nearest end (1e10 as i32 is i32::MAX, -1.5 as u8 is 0), and NaN gives 0, at every optimization level. The full table of as results is in stdlib 2.11.6.
An integer, floating-point or char value as bool is a compile error, cannot cast `i32` as `bool` : write the comparison instead, x != 0 for an integer and x != 0.0 for a floating-point value. The error carries that edit as a fix. bool casts to the integer types as 0 and 1.
Any other pair is a compile error: cannot cast `str` as `i32` (only numeric / bool / char casts, and a payload-less enum to an integer). An allowed as always succeeds. For a conversion that may fail, use .try_into() instead.
#2.14.3. .into() calls
Next, the .into() call.
expr.into()
This desugars to Into::into::<Target>(expr), i.e. Target::from(expr), and requires an implementation of Target: From<typeof(expr)>. The target type is inferred from context, such as the variable's declared type or the parameter type.
let x: i64 = 100i64;
let y: int = x.into(); // int::from(x)
Where the target type cannot be inferred, it can be given with turbofish.
let y = x.into::<int>();
.into() applies only where the standard library registers a value-preserving conversion, i.e. one without information loss. It is generally used to convert from a narrower type to a wider one.
#2.14.4. .try_into() calls
Finally, the .try_into() call.
expr.try_into::<Type>()
This desugars to Target::try_from(expr) (Target: TryFrom<typeof(expr)>). try_into is a throws method: on success it returns a value of the target type, and on failure it throws an error (the target's TryFrom::Error; for numeric conversions OverflowError, stdlib 2.11.4). The call must therefore be marked with try. It is used when the conversion can fail, such as moving a large integer to a smaller integer or a floating-point value to an integer.
let big: i64 = 10_000_000_000i64;
let n = try big.try_into::<i32>() catch e {
...
};
let m: i32 | none = try? big.try_into::<i32>();
#2.14.5. Summary of the three forms
The three forms differ as follows.
| Form | Can fail? | Can lose information? | Trait |
|---|---|---|---|
as | No | Yes | none (built-in) |
.into() | No | No (value-preserving) | From<S> |
.try_into() | Yes (throws an error) | No (on success) | TryFrom<S> |
Choose by situation: use as to change bits or precision intentionally; use .into() when only a safe, lossless widening is needed; use .try_into() to handle the possibility of failure explicitly.
#2.14.6. Context-based automatic conversion
An unsuffixed numeric literal is not converted; its type is determined by the expected type. The 1 in let x: f64 = 1 is f64 from the start. The exact rules are defined in Numeric literals.
Automatic conversion of runtime variables, by contrast, is not allowed. One of the three forms above must always be written. The one exception is a view, not a conversion: a List<T> where a SliceMut<T> is expected is passed as a writable view of the whole list, and xs[a:b] there as a view of that range (stdlib 2.9.7a). Nothing is copied.
let a: i64 = 100i64;
let b: i32 = a; // ERROR: explicit conversion required
let b: i32 = a as i32; // OK
let b: i32 = try! a.try_into::<i32>(); // OK: panics on failure
This explicitness prevents silent loss of precision.
#2.14.7. Where the conversion traits live
From<U> / Into and TryFrom<U> / TryInto are defined in core::convert (standard library tiers). The full matrix of which traits are implemented for which type pairs is defined in the standard library specification. as has no trait; its pairs are the fixed set in 2.14.2.
Found a mistake? Edit this page on GitHub. Last updated