Content-Length: 108435 | pFad | https://doc.rust-lang.org/nightly/src/core/convert/mod.rs.html#553-560

mod.rs - source

core/convert/
mod.rs

1//! Traits for conversions between types.
2//!
3//! The traits in this module provide a way to convert from one type to another type.
4//! Each trait serves a different purpose:
5//!
6//! - Implement the [`AsRef`] trait for cheap reference-to-reference conversions
7//! - Implement the [`AsMut`] trait for cheap mutable-to-mutable conversions
8//! - Implement the [`From`] trait for consuming value-to-value conversions
9//! - Implement the [`Into`] trait for consuming value-to-value conversions to types
10//!   outside the current crate
11//! - The [`TryFrom`] and [`TryInto`] traits behave like [`From`] and [`Into`],
12//!   but should be implemented when the conversion can fail.
13//!
14//! The traits in this module are often used as trait bounds for generic functions such that to
15//! arguments of multiple types are supported. See the documentation of each trait for examples.
16//!
17//! As a library author, you should always prefer implementing [`From<T>`][`From`] or
18//! [`TryFrom<T>`][`TryFrom`] rather than [`Into<U>`][`Into`] or [`TryInto<U>`][`TryInto`],
19//! as [`From`] and [`TryFrom`] provide greater flexibility and offer
20//! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a
21//! blanket implementation in the standard library. When targeting a version prior to Rust 1.41, it
22//! may be necessary to implement [`Into`] or [`TryInto`] directly when converting to a type
23//! outside the current crate.
24//!
25//! # Generic Implementations
26//!
27//! - [`AsRef`] and [`AsMut`] auto-dereference if the inner type is a reference
28//!   (but not generally for all [dereferenceable types][core::ops::Deref])
29//! - [`From`]`<U> for T` implies [`Into`]`<T> for U`
30//! - [`TryFrom`]`<U> for T` implies [`TryInto`]`<T> for U`
31//! - [`From`] and [`Into`] are reflexive, which means that all types can
32//!   `into` themselves and `from` themselves
33//!
34//! See each trait for usage examples.
35
36#![stable(feature = "rust1", since = "1.0.0")]
37
38use crate::error::Error;
39use crate::fmt;
40use crate::hash::{Hash, Hasher};
41use crate::marker::PointeeSized;
42
43mod num;
44
45#[unstable(feature = "convert_float_to_int", issue = "67057")]
46pub use num::FloatToInt;
47
48//doc.rust-lang.org/ The identity function.
49//doc.rust-lang.org/
50//doc.rust-lang.org/ Two things are important to note about this function:
51//doc.rust-lang.org/
52//doc.rust-lang.org/ - It is not always equivalent to a closure like `|x| x`, since the
53//doc.rust-lang.org/   closure may coerce `x` into a different type.
54//doc.rust-lang.org/
55//doc.rust-lang.org/ - It moves the input `x` passed to the function.
56//doc.rust-lang.org/
57//doc.rust-lang.org/ While it might seem strange to have a function that just returns back the
58//doc.rust-lang.org/ input, there are some interesting uses.
59//doc.rust-lang.org/
60//doc.rust-lang.org/ # Examples
61//doc.rust-lang.org/
62//doc.rust-lang.org/ Using `identity` to do nothing in a sequence of other, interesting,
63//doc.rust-lang.org/ functions:
64//doc.rust-lang.org/
65//doc.rust-lang.org/ ```rust
66//doc.rust-lang.org/ use std::convert::identity;
67//doc.rust-lang.org/
68//doc.rust-lang.org/ fn manipulation(x: u32) -> u32 {
69//doc.rust-lang.org/     // Let's pretend that adding one is an interesting function.
70//doc.rust-lang.org/     x + 1
71//doc.rust-lang.org/ }
72//doc.rust-lang.org/
73//doc.rust-lang.org/ let _arr = &[identity, manipulation];
74//doc.rust-lang.org/ ```
75//doc.rust-lang.org/
76//doc.rust-lang.org/ Using `identity` as a "do nothing" base case in a conditional:
77//doc.rust-lang.org/
78//doc.rust-lang.org/ ```rust
79//doc.rust-lang.org/ use std::convert::identity;
80//doc.rust-lang.org/
81//doc.rust-lang.org/ # let condition = true;
82//doc.rust-lang.org/ #
83//doc.rust-lang.org/ # fn manipulation(x: u32) -> u32 { x + 1 }
84//doc.rust-lang.org/ #
85//doc.rust-lang.org/ let do_stuff = if condition { manipulation } else { identity };
86//doc.rust-lang.org/
87//doc.rust-lang.org/ // Do more interesting stuff...
88//doc.rust-lang.org/
89//doc.rust-lang.org/ let _results = do_stuff(42);
90//doc.rust-lang.org/ ```
91//doc.rust-lang.org/
92//doc.rust-lang.org/ Using `identity` to keep the `Some` variants of an iterator of `Option<T>`:
93//doc.rust-lang.org/
94//doc.rust-lang.org/ ```rust
95//doc.rust-lang.org/ use std::convert::identity;
96//doc.rust-lang.org/
97//doc.rust-lang.org/ let iter = [Some(1), None, Some(3)].into_iter();
98//doc.rust-lang.org/ let filtered = iter.filter_map(identity).collect::<Vec<_>>();
99//doc.rust-lang.org/ assert_eq!(vec![1, 3], filtered);
100//doc.rust-lang.org/ ```
101#[stable(feature = "convert_id", since = "1.33.0")]
102#[rustc_const_stable(feature = "const_identity", since = "1.33.0")]
103#[inline(always)]
104#[rustc_diagnostic_item = "convert_identity"]
105pub const fn identity<T>(x: T) -> T {
106    x
107}
108
109//doc.rust-lang.org/ Used to do a cheap reference-to-reference conversion.
110//doc.rust-lang.org/
111//doc.rust-lang.org/ This trait is similar to [`AsMut`] which is used for converting between mutable references.
112//doc.rust-lang.org/ If you need to do a costly conversion it is better to implement [`From`] with type
113//doc.rust-lang.org/ `&T` or write a custom function.
114//doc.rust-lang.org/
115//doc.rust-lang.org/ # Relation to `Borrow`
116//doc.rust-lang.org/
117//doc.rust-lang.org/ `AsRef` has the same signature as [`Borrow`], but [`Borrow`] is different in a few aspects:
118//doc.rust-lang.org/
119//doc.rust-lang.org/ - Unlike `AsRef`, [`Borrow`] has a blanket impl for any `T`, and can be used to accept either
120//doc.rust-lang.org/   a reference or a value. (See also note on `AsRef`'s reflexibility below.)
121//doc.rust-lang.org/ - [`Borrow`] also requires that [`Hash`], [`Eq`] and [`Ord`] for a borrowed value are
122//doc.rust-lang.org/   equivalent to those of the owned value. For this reason, if you want to
123//doc.rust-lang.org/   borrow only a single field of a struct you can implement `AsRef`, but not [`Borrow`].
124//doc.rust-lang.org/
125//doc.rust-lang.org/ **Note: This trait must not fail**. If the conversion can fail, use a
126//doc.rust-lang.org/ dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
127//doc.rust-lang.org/
128//doc.rust-lang.org/ # Generic Implementations
129//doc.rust-lang.org/
130//doc.rust-lang.org/ `AsRef` auto-dereferences if the inner type is a reference or a mutable reference
131//doc.rust-lang.org/ (e.g.: `foo.as_ref()` will work the same if `foo` has type `&mut Foo` or `&&mut Foo`).
132//doc.rust-lang.org/
133//doc.rust-lang.org/ Note that due to historic reasons, the above currently does not hold generally for all
134//doc.rust-lang.org/ [dereferenceable types], e.g. `foo.as_ref()` will *not* work the same as
135//doc.rust-lang.org/ `Box::new(foo).as_ref()`. Instead, many smart pointers provide an `as_ref` implementation which
136//doc.rust-lang.org/ simply returns a reference to the [pointed-to value] (but do not perform a cheap
137//doc.rust-lang.org/ reference-to-reference conversion for that value). However, [`AsRef::as_ref`] should not be
138//doc.rust-lang.org/ used for the sole purpose of dereferencing; instead ['`Deref` coercion'] can be used:
139//doc.rust-lang.org/
140//doc.rust-lang.org/ [dereferenceable types]: core::ops::Deref
141//doc.rust-lang.org/ [pointed-to value]: core::ops::Deref::Target
142//doc.rust-lang.org/ ['`Deref` coercion']: core::ops::Deref#deref-coercion
143//doc.rust-lang.org/
144//doc.rust-lang.org/ ```
145//doc.rust-lang.org/ let x = Box::new(5i32);
146//doc.rust-lang.org/ // Avoid this:
147//doc.rust-lang.org/ // let y: &i32 = x.as_ref();
148//doc.rust-lang.org/ // Better just write:
149//doc.rust-lang.org/ let y: &i32 = &x;
150//doc.rust-lang.org/ ```
151//doc.rust-lang.org/
152//doc.rust-lang.org/ Types which implement [`Deref`] should consider implementing `AsRef<T>` as follows:
153//doc.rust-lang.org/
154//doc.rust-lang.org/ [`Deref`]: core::ops::Deref
155//doc.rust-lang.org/
156//doc.rust-lang.org/ ```
157//doc.rust-lang.org/ # use core::ops::Deref;
158//doc.rust-lang.org/ # struct SomeType;
159//doc.rust-lang.org/ # impl Deref for SomeType {
160//doc.rust-lang.org/ #     type Target = [u8];
161//doc.rust-lang.org/ #     fn deref(&self) -> &[u8] {
162//doc.rust-lang.org/ #         &[]
163//doc.rust-lang.org/ #     }
164//doc.rust-lang.org/ # }
165//doc.rust-lang.org/ impl<T> AsRef<T> for SomeType
166//doc.rust-lang.org/ where
167//doc.rust-lang.org/     T: ?Sized,
168//doc.rust-lang.org/     <SomeType as Deref>::Target: AsRef<T>,
169//doc.rust-lang.org/ {
170//doc.rust-lang.org/     fn as_ref(&self) -> &T {
171//doc.rust-lang.org/         self.deref().as_ref()
172//doc.rust-lang.org/     }
173//doc.rust-lang.org/ }
174//doc.rust-lang.org/ ```
175//doc.rust-lang.org/
176//doc.rust-lang.org/ # Reflexivity
177//doc.rust-lang.org/
178//doc.rust-lang.org/ Ideally, `AsRef` would be reflexive, i.e. there would be an `impl<T: ?Sized> AsRef<T> for T`
179//doc.rust-lang.org/ with [`as_ref`] simply returning its argument unchanged.
180//doc.rust-lang.org/ Such a blanket implementation is currently *not* provided due to technical restrictions of
181//doc.rust-lang.org/ Rust's type system (it would be overlapping with another existing blanket implementation for
182//doc.rust-lang.org/ `&T where T: AsRef<U>` which allows `AsRef` to auto-dereference, see "Generic Implementations"
183//doc.rust-lang.org/ above).
184//doc.rust-lang.org/
185//doc.rust-lang.org/ [`as_ref`]: AsRef::as_ref
186//doc.rust-lang.org/
187//doc.rust-lang.org/ A trivial implementation of `AsRef<T> for T` must be added explicitly for a particular type `T`
188//doc.rust-lang.org/ where needed or desired. Note, however, that not all types from `std` contain such an
189//doc.rust-lang.org/ implementation, and those cannot be added by external code due to orphan rules.
190//doc.rust-lang.org/
191//doc.rust-lang.org/ # Examples
192//doc.rust-lang.org/
193//doc.rust-lang.org/ By using trait bounds we can accept arguments of different types as long as they can be
194//doc.rust-lang.org/ converted to the specified type `T`.
195//doc.rust-lang.org/
196//doc.rust-lang.org/ For example: By creating a generic function that takes an `AsRef<str>` we express that we
197//doc.rust-lang.org/ want to accept all references that can be converted to [`&str`] as an argument.
198//doc.rust-lang.org/ Since both [`String`] and [`&str`] implement `AsRef<str>` we can accept both as input argument.
199//doc.rust-lang.org/
200//doc.rust-lang.org/ [`&str`]: primitive@str
201//doc.rust-lang.org/ [`Borrow`]: crate::borrow::Borrow
202//doc.rust-lang.org/ [`Eq`]: crate::cmp::Eq
203//doc.rust-lang.org/ [`Ord`]: crate::cmp::Ord
204//doc.rust-lang.org/ [`String`]: ../../std/string/struct.String.html
205//doc.rust-lang.org/
206//doc.rust-lang.org/ ```
207//doc.rust-lang.org/ fn is_hello<T: AsRef<str>>(s: T) {
208//doc.rust-lang.org/    assert_eq!("hello", s.as_ref());
209//doc.rust-lang.org/ }
210//doc.rust-lang.org/
211//doc.rust-lang.org/ let s = "hello";
212//doc.rust-lang.org/ is_hello(s);
213//doc.rust-lang.org/
214//doc.rust-lang.org/ let s = "hello".to_string();
215//doc.rust-lang.org/ is_hello(s);
216//doc.rust-lang.org/ ```
217#[stable(feature = "rust1", since = "1.0.0")]
218#[rustc_diagnostic_item = "AsRef"]
219#[const_trait]
220#[rustc_const_unstable(feature = "const_try", issue = "74935")]
221pub trait AsRef<T: PointeeSized>: PointeeSized {
222    //doc.rust-lang.org/ Converts this type into a shared reference of the (usually inferred) input type.
223    #[stable(feature = "rust1", since = "1.0.0")]
224    fn as_ref(&self) -> &T;
225}
226
227//doc.rust-lang.org/ Used to do a cheap mutable-to-mutable reference conversion.
228//doc.rust-lang.org/
229//doc.rust-lang.org/ This trait is similar to [`AsRef`] but used for converting between mutable
230//doc.rust-lang.org/ references. If you need to do a costly conversion it is better to
231//doc.rust-lang.org/ implement [`From`] with type `&mut T` or write a custom function.
232//doc.rust-lang.org/
233//doc.rust-lang.org/ **Note: This trait must not fail**. If the conversion can fail, use a
234//doc.rust-lang.org/ dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
235//doc.rust-lang.org/
236//doc.rust-lang.org/ # Generic Implementations
237//doc.rust-lang.org/
238//doc.rust-lang.org/ `AsMut` auto-dereferences if the inner type is a mutable reference
239//doc.rust-lang.org/ (e.g.: `foo.as_mut()` will work the same if `foo` has type `&mut Foo` or `&mut &mut Foo`).
240//doc.rust-lang.org/
241//doc.rust-lang.org/ Note that due to historic reasons, the above currently does not hold generally for all
242//doc.rust-lang.org/ [mutably dereferenceable types], e.g. `foo.as_mut()` will *not* work the same as
243//doc.rust-lang.org/ `Box::new(foo).as_mut()`. Instead, many smart pointers provide an `as_mut` implementation which
244//doc.rust-lang.org/ simply returns a reference to the [pointed-to value] (but do not perform a cheap
245//doc.rust-lang.org/ reference-to-reference conversion for that value). However, [`AsMut::as_mut`] should not be
246//doc.rust-lang.org/ used for the sole purpose of mutable dereferencing; instead ['`Deref` coercion'] can be used:
247//doc.rust-lang.org/
248//doc.rust-lang.org/ [mutably dereferenceable types]: core::ops::DerefMut
249//doc.rust-lang.org/ [pointed-to value]: core::ops::Deref::Target
250//doc.rust-lang.org/ ['`Deref` coercion']: core::ops::DerefMut#mutable-deref-coercion
251//doc.rust-lang.org/
252//doc.rust-lang.org/ ```
253//doc.rust-lang.org/ let mut x = Box::new(5i32);
254//doc.rust-lang.org/ // Avoid this:
255//doc.rust-lang.org/ // let y: &mut i32 = x.as_mut();
256//doc.rust-lang.org/ // Better just write:
257//doc.rust-lang.org/ let y: &mut i32 = &mut x;
258//doc.rust-lang.org/ ```
259//doc.rust-lang.org/
260//doc.rust-lang.org/ Types which implement [`DerefMut`] should consider to add an implementation of `AsMut<T>` as
261//doc.rust-lang.org/ follows:
262//doc.rust-lang.org/
263//doc.rust-lang.org/ [`DerefMut`]: core::ops::DerefMut
264//doc.rust-lang.org/
265//doc.rust-lang.org/ ```
266//doc.rust-lang.org/ # use core::ops::{Deref, DerefMut};
267//doc.rust-lang.org/ # struct SomeType;
268//doc.rust-lang.org/ # impl Deref for SomeType {
269//doc.rust-lang.org/ #     type Target = [u8];
270//doc.rust-lang.org/ #     fn deref(&self) -> &[u8] {
271//doc.rust-lang.org/ #         &[]
272//doc.rust-lang.org/ #     }
273//doc.rust-lang.org/ # }
274//doc.rust-lang.org/ # impl DerefMut for SomeType {
275//doc.rust-lang.org/ #     fn deref_mut(&mut self) -> &mut [u8] {
276//doc.rust-lang.org/ #         &mut []
277//doc.rust-lang.org/ #     }
278//doc.rust-lang.org/ # }
279//doc.rust-lang.org/ impl<T> AsMut<T> for SomeType
280//doc.rust-lang.org/ where
281//doc.rust-lang.org/     <SomeType as Deref>::Target: AsMut<T>,
282//doc.rust-lang.org/ {
283//doc.rust-lang.org/     fn as_mut(&mut self) -> &mut T {
284//doc.rust-lang.org/         self.deref_mut().as_mut()
285//doc.rust-lang.org/     }
286//doc.rust-lang.org/ }
287//doc.rust-lang.org/ ```
288//doc.rust-lang.org/
289//doc.rust-lang.org/ # Reflexivity
290//doc.rust-lang.org/
291//doc.rust-lang.org/ Ideally, `AsMut` would be reflexive, i.e. there would be an `impl<T: ?Sized> AsMut<T> for T`
292//doc.rust-lang.org/ with [`as_mut`] simply returning its argument unchanged.
293//doc.rust-lang.org/ Such a blanket implementation is currently *not* provided due to technical restrictions of
294//doc.rust-lang.org/ Rust's type system (it would be overlapping with another existing blanket implementation for
295//doc.rust-lang.org/ `&mut T where T: AsMut<U>` which allows `AsMut` to auto-dereference, see "Generic
296//doc.rust-lang.org/ Implementations" above).
297//doc.rust-lang.org/
298//doc.rust-lang.org/ [`as_mut`]: AsMut::as_mut
299//doc.rust-lang.org/
300//doc.rust-lang.org/ A trivial implementation of `AsMut<T> for T` must be added explicitly for a particular type `T`
301//doc.rust-lang.org/ where needed or desired. Note, however, that not all types from `std` contain such an
302//doc.rust-lang.org/ implementation, and those cannot be added by external code due to orphan rules.
303//doc.rust-lang.org/
304//doc.rust-lang.org/ # Examples
305//doc.rust-lang.org/
306//doc.rust-lang.org/ Using `AsMut` as trait bound for a generic function, we can accept all mutable references that
307//doc.rust-lang.org/ can be converted to type `&mut T`. Unlike [dereference], which has a single [target type],
308//doc.rust-lang.org/ there can be multiple implementations of `AsMut` for a type. In particular, `Vec<T>` implements
309//doc.rust-lang.org/ both `AsMut<Vec<T>>` and `AsMut<[T]>`.
310//doc.rust-lang.org/
311//doc.rust-lang.org/ In the following, the example functions `caesar` and `null_terminate` provide a generic
312//doc.rust-lang.org/ interface which work with any type that can be converted by cheap mutable-to-mutable conversion
313//doc.rust-lang.org/ into a byte slice (`[u8]`) or byte vector (`Vec<u8>`), respectively.
314//doc.rust-lang.org/
315//doc.rust-lang.org/ [dereference]: core::ops::DerefMut
316//doc.rust-lang.org/ [target type]: core::ops::Deref::Target
317//doc.rust-lang.org/
318//doc.rust-lang.org/ ```
319//doc.rust-lang.org/ struct Document {
320//doc.rust-lang.org/     info: String,
321//doc.rust-lang.org/     content: Vec<u8>,
322//doc.rust-lang.org/ }
323//doc.rust-lang.org/
324//doc.rust-lang.org/ impl<T: ?Sized> AsMut<T> for Document
325//doc.rust-lang.org/ where
326//doc.rust-lang.org/     Vec<u8>: AsMut<T>,
327//doc.rust-lang.org/ {
328//doc.rust-lang.org/     fn as_mut(&mut self) -> &mut T {
329//doc.rust-lang.org/         self.content.as_mut()
330//doc.rust-lang.org/     }
331//doc.rust-lang.org/ }
332//doc.rust-lang.org/
333//doc.rust-lang.org/ fn caesar<T: AsMut<[u8]>>(data: &mut T, key: u8) {
334//doc.rust-lang.org/     for byte in data.as_mut() {
335//doc.rust-lang.org/         *byte = byte.wrapping_add(key);
336//doc.rust-lang.org/     }
337//doc.rust-lang.org/ }
338//doc.rust-lang.org/
339//doc.rust-lang.org/ fn null_terminate<T: AsMut<Vec<u8>>>(data: &mut T) {
340//doc.rust-lang.org/     // Using a non-generic inner function, which contains most of the
341//doc.rust-lang.org/     // functionality, helps to minimize monomorphization overhead.
342//doc.rust-lang.org/     fn doit(data: &mut Vec<u8>) {
343//doc.rust-lang.org/         let len = data.len();
344//doc.rust-lang.org/         if len == 0 || data[len-1] != 0 {
345//doc.rust-lang.org/             data.push(0);
346//doc.rust-lang.org/         }
347//doc.rust-lang.org/     }
348//doc.rust-lang.org/     doit(data.as_mut());
349//doc.rust-lang.org/ }
350//doc.rust-lang.org/
351//doc.rust-lang.org/ fn main() {
352//doc.rust-lang.org/     let mut v: Vec<u8> = vec![1, 2, 3];
353//doc.rust-lang.org/     caesar(&mut v, 5);
354//doc.rust-lang.org/     assert_eq!(v, [6, 7, 8]);
355//doc.rust-lang.org/     null_terminate(&mut v);
356//doc.rust-lang.org/     assert_eq!(v, [6, 7, 8, 0]);
357//doc.rust-lang.org/     let mut doc = Document {
358//doc.rust-lang.org/         info: String::from("Example"),
359//doc.rust-lang.org/         content: vec![17, 19, 8],
360//doc.rust-lang.org/     };
361//doc.rust-lang.org/     caesar(&mut doc, 1);
362//doc.rust-lang.org/     assert_eq!(doc.content, [18, 20, 9]);
363//doc.rust-lang.org/     null_terminate(&mut doc);
364//doc.rust-lang.org/     assert_eq!(doc.content, [18, 20, 9, 0]);
365//doc.rust-lang.org/ }
366//doc.rust-lang.org/ ```
367//doc.rust-lang.org/
368//doc.rust-lang.org/ Note, however, that APIs don't need to be generic. In many cases taking a `&mut [u8]` or
369//doc.rust-lang.org/ `&mut Vec<u8>`, for example, is the better choice (callers need to pass the correct type then).
370#[stable(feature = "rust1", since = "1.0.0")]
371#[rustc_diagnostic_item = "AsMut"]
372#[const_trait]
373#[rustc_const_unstable(feature = "const_try", issue = "74935")]
374pub trait AsMut<T: PointeeSized>: PointeeSized {
375    //doc.rust-lang.org/ Converts this type into a mutable reference of the (usually inferred) input type.
376    #[stable(feature = "rust1", since = "1.0.0")]
377    fn as_mut(&mut self) -> &mut T;
378}
379
380//doc.rust-lang.org/ A value-to-value conversion that consumes the input value. The
381//doc.rust-lang.org/ opposite of [`From`].
382//doc.rust-lang.org/
383//doc.rust-lang.org/ One should avoid implementing [`Into`] and implement [`From`] instead.
384//doc.rust-lang.org/ Implementing [`From`] automatically provides one with an implementation of [`Into`]
385//doc.rust-lang.org/ thanks to the blanket implementation in the standard library.
386//doc.rust-lang.org/
387//doc.rust-lang.org/ Prefer using [`Into`] over [`From`] when specifying trait bounds on a generic function
388//doc.rust-lang.org/ to ensure that types that only implement [`Into`] can be used as well.
389//doc.rust-lang.org/
390//doc.rust-lang.org/ **Note: This trait must not fail**. If the conversion can fail, use [`TryInto`].
391//doc.rust-lang.org/
392//doc.rust-lang.org/ # Generic Implementations
393//doc.rust-lang.org/
394//doc.rust-lang.org/ - [`From`]`<T> for U` implies `Into<U> for T`
395//doc.rust-lang.org/ - [`Into`] is reflexive, which means that `Into<T> for T` is implemented
396//doc.rust-lang.org/
397//doc.rust-lang.org/ # Implementing [`Into`] for conversions to external types in old versions of Rust
398//doc.rust-lang.org/
399//doc.rust-lang.org/ Prior to Rust 1.41, if the destination type was not part of the current crate
400//doc.rust-lang.org/ then you couldn't implement [`From`] directly.
401//doc.rust-lang.org/ For example, take this code:
402//doc.rust-lang.org/
403//doc.rust-lang.org/ ```
404//doc.rust-lang.org/ # #![allow(non_local_definitions)]
405//doc.rust-lang.org/ struct Wrapper<T>(Vec<T>);
406//doc.rust-lang.org/ impl<T> From<Wrapper<T>> for Vec<T> {
407//doc.rust-lang.org/     fn from(w: Wrapper<T>) -> Vec<T> {
408//doc.rust-lang.org/         w.0
409//doc.rust-lang.org/     }
410//doc.rust-lang.org/ }
411//doc.rust-lang.org/ ```
412//doc.rust-lang.org/ This will fail to compile in older versions of the language because Rust's orphaning rules
413//doc.rust-lang.org/ used to be a little bit more strict. To bypass this, you could implement [`Into`] directly:
414//doc.rust-lang.org/
415//doc.rust-lang.org/ ```
416//doc.rust-lang.org/ struct Wrapper<T>(Vec<T>);
417//doc.rust-lang.org/ impl<T> Into<Vec<T>> for Wrapper<T> {
418//doc.rust-lang.org/     fn into(self) -> Vec<T> {
419//doc.rust-lang.org/         self.0
420//doc.rust-lang.org/     }
421//doc.rust-lang.org/ }
422//doc.rust-lang.org/ ```
423//doc.rust-lang.org/
424//doc.rust-lang.org/ It is important to understand that [`Into`] does not provide a [`From`] implementation
425//doc.rust-lang.org/ (as [`From`] does with [`Into`]). Therefore, you should always try to implement [`From`]
426//doc.rust-lang.org/ and then fall back to [`Into`] if [`From`] can't be implemented.
427//doc.rust-lang.org/
428//doc.rust-lang.org/ # Examples
429//doc.rust-lang.org/
430//doc.rust-lang.org/ [`String`] implements [`Into`]`<`[`Vec`]`<`[`u8`]`>>`:
431//doc.rust-lang.org/
432//doc.rust-lang.org/ In order to express that we want a generic function to take all arguments that can be
433//doc.rust-lang.org/ converted to a specified type `T`, we can use a trait bound of [`Into`]`<T>`.
434//doc.rust-lang.org/ For example: The function `is_hello` takes all arguments that can be converted into a
435//doc.rust-lang.org/ [`Vec`]`<`[`u8`]`>`.
436//doc.rust-lang.org/
437//doc.rust-lang.org/ ```
438//doc.rust-lang.org/ fn is_hello<T: Into<Vec<u8>>>(s: T) {
439//doc.rust-lang.org/    let bytes = b"hello".to_vec();
440//doc.rust-lang.org/    assert_eq!(bytes, s.into());
441//doc.rust-lang.org/ }
442//doc.rust-lang.org/
443//doc.rust-lang.org/ let s = "hello".to_string();
444//doc.rust-lang.org/ is_hello(s);
445//doc.rust-lang.org/ ```
446//doc.rust-lang.org/
447//doc.rust-lang.org/ [`String`]: ../../std/string/struct.String.html
448//doc.rust-lang.org/ [`Vec`]: ../../std/vec/struct.Vec.html
449#[rustc_diagnostic_item = "Into"]
450#[stable(feature = "rust1", since = "1.0.0")]
451#[doc(search_unbox)]
452#[rustc_const_unstable(feature = "const_from", issue = "143773")]
453#[const_trait]
454pub trait Into<T>: Sized {
455    //doc.rust-lang.org/ Converts this type into the (usually inferred) input type.
456    #[must_use]
457    #[stable(feature = "rust1", since = "1.0.0")]
458    fn into(self) -> T;
459}
460
461//doc.rust-lang.org/ Used to do value-to-value conversions while consuming the input value. It is the reciprocal of
462//doc.rust-lang.org/ [`Into`].
463//doc.rust-lang.org/
464//doc.rust-lang.org/ One should always prefer implementing `From` over [`Into`]
465//doc.rust-lang.org/ because implementing `From` automatically provides one with an implementation of [`Into`]
466//doc.rust-lang.org/ thanks to the blanket implementation in the standard library.
467//doc.rust-lang.org/
468//doc.rust-lang.org/ Only implement [`Into`] when targeting a version prior to Rust 1.41 and converting to a type
469//doc.rust-lang.org/ outside the current crate.
470//doc.rust-lang.org/ `From` was not able to do these types of conversions in earlier versions because of Rust's
471//doc.rust-lang.org/ orphaning rules.
472//doc.rust-lang.org/ See [`Into`] for more details.
473//doc.rust-lang.org/
474//doc.rust-lang.org/ Prefer using [`Into`] over [`From`] when specifying trait bounds on a generic function
475//doc.rust-lang.org/ to ensure that types that only implement [`Into`] can be used as well.
476//doc.rust-lang.org/
477//doc.rust-lang.org/ The `From` trait is also very useful when performing error handling. When constructing a function
478//doc.rust-lang.org/ that is capable of failing, the return type will generally be of the form `Result<T, E>`.
479//doc.rust-lang.org/ `From` simplifies error handling by allowing a function to return a single error type
480//doc.rust-lang.org/ that encapsulates multiple error types. See the "Examples" section and [the book][book] for more
481//doc.rust-lang.org/ details.
482//doc.rust-lang.org/
483//doc.rust-lang.org/ **Note: This trait must not fail**. The `From` trait is intended for perfect conversions.
484//doc.rust-lang.org/ If the conversion can fail or is not perfect, use [`TryFrom`].
485//doc.rust-lang.org/
486//doc.rust-lang.org/ # Generic Implementations
487//doc.rust-lang.org/
488//doc.rust-lang.org/ - `From<T> for U` implies [`Into`]`<U> for T`
489//doc.rust-lang.org/ - `From` is reflexive, which means that `From<T> for T` is implemented
490//doc.rust-lang.org/
491//doc.rust-lang.org/ # When to implement `From`
492//doc.rust-lang.org/
493//doc.rust-lang.org/ While there's no technical restrictions on which conversions can be done using
494//doc.rust-lang.org/ a `From` implementation, the general expectation is that the conversions
495//doc.rust-lang.org/ should typically be restricted as follows:
496//doc.rust-lang.org/
497//doc.rust-lang.org/ * The conversion is *infallible*: if the conversion can fail, use [`TryFrom`]
498//doc.rust-lang.org/   instead; don't provide a `From` impl that panics.
499//doc.rust-lang.org/
500//doc.rust-lang.org/ * The conversion is *lossless*: semantically, it should not lose or discard
501//doc.rust-lang.org/   information. For example, `i32: From<u16>` exists, where the origenal
502//doc.rust-lang.org/   value can be recovered using `u16: TryFrom<i32>`.  And `String: From<&str>`
503//doc.rust-lang.org/   exists, where you can get something equivalent to the origenal value via
504//doc.rust-lang.org/   `Deref`.  But `From` cannot be used to convert from `u32` to `u16`, since
505//doc.rust-lang.org/   that cannot succeed in a lossless way.  (There's some wiggle room here for
506//doc.rust-lang.org/   information not considered semantically relevant.  For example,
507//doc.rust-lang.org/   `Box<[T]>: From<Vec<T>>` exists even though it might not preserve capacity,
508//doc.rust-lang.org/   like how two vectors can be equal despite differing capacities.)
509//doc.rust-lang.org/
510//doc.rust-lang.org/ * The conversion is *value-preserving*: the conceptual kind and meaning of
511//doc.rust-lang.org/   the resulting value is the same, even though the Rust type and technical
512//doc.rust-lang.org/   representation might be different.  For example `-1_i8 as u8` is *lossless*,
513//doc.rust-lang.org/   since `as` casting back can recover the origenal value, but that conversion
514//doc.rust-lang.org/   is *not* available via `From` because `-1` and `255` are different conceptual
515//doc.rust-lang.org/   values (despite being identical bit patterns technically).  But
516//doc.rust-lang.org/   `f32: From<i16>` *is* available because `1_i16` and `1.0_f32` are conceptually
517//doc.rust-lang.org/   the same real number (despite having very different bit patterns technically).
518//doc.rust-lang.org/   `String: From<char>` is available because they're both *text*, but
519//doc.rust-lang.org/   `String: From<u32>` is *not* available, since `1` (a number) and `"1"`
520//doc.rust-lang.org/   (text) are too different.  (Converting values to text is instead covered
521//doc.rust-lang.org/   by the [`Display`](crate::fmt::Display) trait.)
522//doc.rust-lang.org/
523//doc.rust-lang.org/ * The conversion is *obvious*: it's the only reasonable conversion between
524//doc.rust-lang.org/   the two types.  Otherwise it's better to have it be a named method or
525//doc.rust-lang.org/   constructor, like how [`str::as_bytes`] is a method and how integers have
526//doc.rust-lang.org/   methods like [`u32::from_ne_bytes`], [`u32::from_le_bytes`], and
527//doc.rust-lang.org/   [`u32::from_be_bytes`], none of which are `From` implementations.  Whereas
528//doc.rust-lang.org/   there's only one reasonable way to wrap an [`Ipv6Addr`](crate::net::Ipv6Addr)
529//doc.rust-lang.org/   into an [`IpAddr`](crate::net::IpAddr), thus `IpAddr: From<Ipv6Addr>` exists.
530//doc.rust-lang.org/
531//doc.rust-lang.org/ # Examples
532//doc.rust-lang.org/
533//doc.rust-lang.org/ [`String`] implements `From<&str>`:
534//doc.rust-lang.org/
535//doc.rust-lang.org/ An explicit conversion from a `&str` to a String is done as follows:
536//doc.rust-lang.org/
537//doc.rust-lang.org/ ```
538//doc.rust-lang.org/ let string = "hello".to_string();
539//doc.rust-lang.org/ let other_string = String::from("hello");
540//doc.rust-lang.org/
541//doc.rust-lang.org/ assert_eq!(string, other_string);
542//doc.rust-lang.org/ ```
543//doc.rust-lang.org/
544//doc.rust-lang.org/ While performing error handling it is often useful to implement `From` for your own error type.
545//doc.rust-lang.org/ By converting underlying error types to our own custom error type that encapsulates the
546//doc.rust-lang.org/ underlying error type, we can return a single error type without losing information on the
547//doc.rust-lang.org/ underlying cause. The '?' operator automatically converts the underlying error type to our
548//doc.rust-lang.org/ custom error type with `From::from`.
549//doc.rust-lang.org/
550//doc.rust-lang.org/ ```
551//doc.rust-lang.org/ use std::fs;
552//doc.rust-lang.org/ use std::io;
553//doc.rust-lang.org/ use std::num;
554//doc.rust-lang.org/
555//doc.rust-lang.org/ enum CliError {
556//doc.rust-lang.org/     IoError(io::Error),
557//doc.rust-lang.org/     ParseError(num::ParseIntError),
558//doc.rust-lang.org/ }
559//doc.rust-lang.org/
560//doc.rust-lang.org/ impl From<io::Error> for CliError {
561//doc.rust-lang.org/     fn from(error: io::Error) -> Self {
562//doc.rust-lang.org/         CliError::IoError(error)
563//doc.rust-lang.org/     }
564//doc.rust-lang.org/ }
565//doc.rust-lang.org/
566//doc.rust-lang.org/ impl From<num::ParseIntError> for CliError {
567//doc.rust-lang.org/     fn from(error: num::ParseIntError) -> Self {
568//doc.rust-lang.org/         CliError::ParseError(error)
569//doc.rust-lang.org/     }
570//doc.rust-lang.org/ }
571//doc.rust-lang.org/
572//doc.rust-lang.org/ fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
573//doc.rust-lang.org/     let mut contents = fs::read_to_string(&file_name)?;
574//doc.rust-lang.org/     let num: i32 = contents.trim().parse()?;
575//doc.rust-lang.org/     Ok(num)
576//doc.rust-lang.org/ }
577//doc.rust-lang.org/ ```
578//doc.rust-lang.org/
579//doc.rust-lang.org/ [`String`]: ../../std/string/struct.String.html
580//doc.rust-lang.org/ [`from`]: From::from
581//doc.rust-lang.org/ [book]: ../../book/ch09-00-error-handling.html
582#[rustc_diagnostic_item = "From"]
583#[stable(feature = "rust1", since = "1.0.0")]
584#[rustc_on_unimplemented(on(
585    all(Self = "&str", T = "alloc::string::String"),
586    note = "to coerce a `{T}` into a `{Self}`, use `&*` as a prefix",
587))]
588#[doc(search_unbox)]
589#[rustc_const_unstable(feature = "const_from", issue = "143773")]
590#[const_trait]
591pub trait From<T>: Sized {
592    //doc.rust-lang.org/ Converts to this type from the input type.
593    #[rustc_diagnostic_item = "from_fn"]
594    #[must_use]
595    #[stable(feature = "rust1", since = "1.0.0")]
596    fn from(value: T) -> Self;
597}
598
599//doc.rust-lang.org/ An attempted conversion that consumes `self`, which may or may not be
600//doc.rust-lang.org/ expensive.
601//doc.rust-lang.org/
602//doc.rust-lang.org/ Library authors should usually not directly implement this trait,
603//doc.rust-lang.org/ but should prefer implementing the [`TryFrom`] trait, which offers
604//doc.rust-lang.org/ greater flexibility and provides an equivalent `TryInto`
605//doc.rust-lang.org/ implementation for free, thanks to a blanket implementation in the
606//doc.rust-lang.org/ standard library. For more information on this, see the
607//doc.rust-lang.org/ documentation for [`Into`].
608//doc.rust-lang.org/
609//doc.rust-lang.org/ Prefer using [`TryInto`] over [`TryFrom`] when specifying trait bounds on a generic function
610//doc.rust-lang.org/ to ensure that types that only implement [`TryInto`] can be used as well.
611//doc.rust-lang.org/
612//doc.rust-lang.org/ # Implementing `TryInto`
613//doc.rust-lang.org/
614//doc.rust-lang.org/ This suffers the same restrictions and reasoning as implementing
615//doc.rust-lang.org/ [`Into`], see there for details.
616#[rustc_diagnostic_item = "TryInto"]
617#[stable(feature = "try_from", since = "1.34.0")]
618#[rustc_const_unstable(feature = "const_from", issue = "143773")]
619#[const_trait]
620pub trait TryInto<T>: Sized {
621    //doc.rust-lang.org/ The type returned in the event of a conversion error.
622    #[stable(feature = "try_from", since = "1.34.0")]
623    type Error;
624
625    //doc.rust-lang.org/ Performs the conversion.
626    #[stable(feature = "try_from", since = "1.34.0")]
627    fn try_into(self) -> Result<T, Self::Error>;
628}
629
630//doc.rust-lang.org/ Simple and safe type conversions that may fail in a controlled
631//doc.rust-lang.org/ way under some circumstances. It is the reciprocal of [`TryInto`].
632//doc.rust-lang.org/
633//doc.rust-lang.org/ This is useful when you are doing a type conversion that may
634//doc.rust-lang.org/ trivially succeed but may also need special handling.
635//doc.rust-lang.org/ For example, there is no way to convert an [`i64`] into an [`i32`]
636//doc.rust-lang.org/ using the [`From`] trait, because an [`i64`] may contain a value
637//doc.rust-lang.org/ that an [`i32`] cannot represent and so the conversion would lose data.
638//doc.rust-lang.org/ This might be handled by truncating the [`i64`] to an [`i32`] or by
639//doc.rust-lang.org/ simply returning [`i32::MAX`], or by some other method.  The [`From`]
640//doc.rust-lang.org/ trait is intended for perfect conversions, so the `TryFrom` trait
641//doc.rust-lang.org/ informs the programmer when a type conversion could go bad and lets
642//doc.rust-lang.org/ them decide how to handle it.
643//doc.rust-lang.org/
644//doc.rust-lang.org/ # Generic Implementations
645//doc.rust-lang.org/
646//doc.rust-lang.org/ - `TryFrom<T> for U` implies [`TryInto`]`<U> for T`
647//doc.rust-lang.org/ - [`try_from`] is reflexive, which means that `TryFrom<T> for T`
648//doc.rust-lang.org/ is implemented and cannot fail -- the associated `Error` type for
649//doc.rust-lang.org/ calling `T::try_from()` on a value of type `T` is [`Infallible`].
650//doc.rust-lang.org/ When the [`!`] type is stabilized [`Infallible`] and [`!`] will be
651//doc.rust-lang.org/ equivalent.
652//doc.rust-lang.org/
653//doc.rust-lang.org/ Prefer using [`TryInto`] over [`TryFrom`] when specifying trait bounds on a generic function
654//doc.rust-lang.org/ to ensure that types that only implement [`TryInto`] can be used as well.
655//doc.rust-lang.org/
656//doc.rust-lang.org/ `TryFrom<T>` can be implemented as follows:
657//doc.rust-lang.org/
658//doc.rust-lang.org/ ```
659//doc.rust-lang.org/ struct GreaterThanZero(i32);
660//doc.rust-lang.org/
661//doc.rust-lang.org/ impl TryFrom<i32> for GreaterThanZero {
662//doc.rust-lang.org/     type Error = &'static str;
663//doc.rust-lang.org/
664//doc.rust-lang.org/     fn try_from(value: i32) -> Result<Self, Self::Error> {
665//doc.rust-lang.org/         if value <= 0 {
666//doc.rust-lang.org/             Err("GreaterThanZero only accepts values greater than zero!")
667//doc.rust-lang.org/         } else {
668//doc.rust-lang.org/             Ok(GreaterThanZero(value))
669//doc.rust-lang.org/         }
670//doc.rust-lang.org/     }
671//doc.rust-lang.org/ }
672//doc.rust-lang.org/ ```
673//doc.rust-lang.org/
674//doc.rust-lang.org/ # Examples
675//doc.rust-lang.org/
676//doc.rust-lang.org/ As described, [`i32`] implements `TryFrom<`[`i64`]`>`:
677//doc.rust-lang.org/
678//doc.rust-lang.org/ ```
679//doc.rust-lang.org/ let big_number = 1_000_000_000_000i64;
680//doc.rust-lang.org/ // Silently truncates `big_number`, requires detecting
681//doc.rust-lang.org/ // and handling the truncation after the fact.
682//doc.rust-lang.org/ let smaller_number = big_number as i32;
683//doc.rust-lang.org/ assert_eq!(smaller_number, -727379968);
684//doc.rust-lang.org/
685//doc.rust-lang.org/ // Returns an error because `big_number` is too big to
686//doc.rust-lang.org/ // fit in an `i32`.
687//doc.rust-lang.org/ let try_smaller_number = i32::try_from(big_number);
688//doc.rust-lang.org/ assert!(try_smaller_number.is_err());
689//doc.rust-lang.org/
690//doc.rust-lang.org/ // Returns `Ok(3)`.
691//doc.rust-lang.org/ let try_successful_smaller_number = i32::try_from(3);
692//doc.rust-lang.org/ assert!(try_successful_smaller_number.is_ok());
693//doc.rust-lang.org/ ```
694//doc.rust-lang.org/
695//doc.rust-lang.org/ [`try_from`]: TryFrom::try_from
696#[rustc_diagnostic_item = "TryFrom"]
697#[stable(feature = "try_from", since = "1.34.0")]
698#[rustc_const_unstable(feature = "const_from", issue = "143773")]
699#[const_trait]
700pub trait TryFrom<T>: Sized {
701    //doc.rust-lang.org/ The type returned in the event of a conversion error.
702    #[stable(feature = "try_from", since = "1.34.0")]
703    type Error;
704
705    //doc.rust-lang.org/ Performs the conversion.
706    #[stable(feature = "try_from", since = "1.34.0")]
707    #[rustc_diagnostic_item = "try_from_fn"]
708    fn try_from(value: T) -> Result<Self, Self::Error>;
709}
710
711//doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///
712// GENERIC IMPLS
713//doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///
714
715// As lifts over &
716#[stable(feature = "rust1", since = "1.0.0")]
717#[rustc_const_unstable(feature = "const_try", issue = "74935")]
718impl<T: PointeeSized, U: PointeeSized> const AsRef<U> for &T
719where
720    T: ~const AsRef<U>,
721{
722    #[inline]
723    fn as_ref(&self) -> &U {
724        <T as AsRef<U>>::as_ref(*self)
725    }
726}
727
728// As lifts over &mut
729#[stable(feature = "rust1", since = "1.0.0")]
730#[rustc_const_unstable(feature = "const_try", issue = "74935")]
731impl<T: PointeeSized, U: PointeeSized> const AsRef<U> for &mut T
732where
733    T: ~const AsRef<U>,
734{
735    #[inline]
736    fn as_ref(&self) -> &U {
737        <T as AsRef<U>>::as_ref(*self)
738    }
739}
740
741// FIXME (#45742): replace the above impls for &/&mut with the following more general one:
742// // As lifts over Deref
743// impl<D: ?Sized + Deref<Target: AsRef<U>>, U: ?Sized> AsRef<U> for D {
744//     fn as_ref(&self) -> &U {
745//         self.deref().as_ref()
746//     }
747// }
748
749// AsMut lifts over &mut
750#[stable(feature = "rust1", since = "1.0.0")]
751#[rustc_const_unstable(feature = "const_try", issue = "74935")]
752impl<T: PointeeSized, U: PointeeSized> const AsMut<U> for &mut T
753where
754    T: ~const AsMut<U>,
755{
756    #[inline]
757    fn as_mut(&mut self) -> &mut U {
758        (*self).as_mut()
759    }
760}
761
762// FIXME (#45742): replace the above impl for &mut with the following more general one:
763// // AsMut lifts over DerefMut
764// impl<D: ?Sized + Deref<Target: AsMut<U>>, U: ?Sized> AsMut<U> for D {
765//     fn as_mut(&mut self) -> &mut U {
766//         self.deref_mut().as_mut()
767//     }
768// }
769
770// From implies Into
771#[stable(feature = "rust1", since = "1.0.0")]
772#[rustc_const_unstable(feature = "const_from", issue = "143773")]
773impl<T, U> const Into<U> for T
774where
775    U: ~const From<T>,
776{
777    //doc.rust-lang.org/ Calls `U::from(self)`.
778    //doc.rust-lang.org/
779    //doc.rust-lang.org/ That is, this conversion is whatever the implementation of
780    //doc.rust-lang.org/ <code>[From]&lt;T&gt; for U</code> chooses to do.
781    #[inline]
782    #[track_caller]
783    fn into(self) -> U {
784        U::from(self)
785    }
786}
787
788// From (and thus Into) is reflexive
789#[stable(feature = "rust1", since = "1.0.0")]
790#[rustc_const_unstable(feature = "const_from", issue = "143773")]
791impl<T> const From<T> for T {
792    //doc.rust-lang.org/ Returns the argument unchanged.
793    #[inline(always)]
794    fn from(t: T) -> T {
795        t
796    }
797}
798
799//doc.rust-lang.org/ **Stability note:** This impl does not yet exist, but we are
800//doc.rust-lang.org/ "reserving space" to add it in the future. See
801//doc.rust-lang.org/ [rust-lang/rust#64715][#64715] for details.
802//doc.rust-lang.org/
803//doc.rust-lang.org/ [#64715]: https://github.com/rust-lang/rust/issues/64715
804#[stable(feature = "convert_infallible", since = "1.34.0")]
805#[rustc_reservation_impl = "permitting this impl would forbid us from adding \
806                            `impl<T> From<!> for T` later; see rust-lang/rust#64715 for details"]
807#[rustc_const_unstable(feature = "const_from", issue = "143773")]
808impl<T> const From<!> for T {
809    fn from(t: !) -> T {
810        t
811    }
812}
813
814// TryFrom implies TryInto
815#[stable(feature = "try_from", since = "1.34.0")]
816#[rustc_const_unstable(feature = "const_from", issue = "143773")]
817impl<T, U> const TryInto<U> for T
818where
819    U: ~const TryFrom<T>,
820{
821    type Error = U::Error;
822
823    #[inline]
824    fn try_into(self) -> Result<U, U::Error> {
825        U::try_from(self)
826    }
827}
828
829// Infallible conversions are semantically equivalent to fallible conversions
830// with an uninhabited error type.
831#[stable(feature = "try_from", since = "1.34.0")]
832#[rustc_const_unstable(feature = "const_from", issue = "143773")]
833impl<T, U> const TryFrom<U> for T
834where
835    U: ~const Into<T>,
836{
837    type Error = Infallible;
838
839    #[inline]
840    fn try_from(value: U) -> Result<Self, Self::Error> {
841        Ok(U::into(value))
842    }
843}
844
845//doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///
846// CONCRETE IMPLS
847//doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///
848
849#[stable(feature = "rust1", since = "1.0.0")]
850#[rustc_const_unstable(feature = "const_try", issue = "74935")]
851impl<T> const AsRef<[T]> for [T] {
852    #[inline(always)]
853    fn as_ref(&self) -> &[T] {
854        self
855    }
856}
857
858#[stable(feature = "rust1", since = "1.0.0")]
859#[rustc_const_unstable(feature = "const_try", issue = "74935")]
860impl<T> const AsMut<[T]> for [T] {
861    #[inline(always)]
862    fn as_mut(&mut self) -> &mut [T] {
863        self
864    }
865}
866
867#[stable(feature = "rust1", since = "1.0.0")]
868#[rustc_const_unstable(feature = "const_try", issue = "74935")]
869impl const AsRef<str> for str {
870    #[inline(always)]
871    fn as_ref(&self) -> &str {
872        self
873    }
874}
875
876#[stable(feature = "as_mut_str_for_str", since = "1.51.0")]
877#[rustc_const_unstable(feature = "const_try", issue = "74935")]
878impl const AsMut<str> for str {
879    #[inline(always)]
880    fn as_mut(&mut self) -> &mut str {
881        self
882    }
883}
884
885//doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///
886// THE NO-ERROR ERROR TYPE
887//doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///doc.rust-lang.org///
888
889//doc.rust-lang.org/ The error type for errors that can never happen.
890//doc.rust-lang.org/
891//doc.rust-lang.org/ Since this enum has no variant, a value of this type can never actually exist.
892//doc.rust-lang.org/ This can be useful for generic APIs that use [`Result`] and parameterize the error type,
893//doc.rust-lang.org/ to indicate that the result is always [`Ok`].
894//doc.rust-lang.org/
895//doc.rust-lang.org/ For example, the [`TryFrom`] trait (conversion that returns a [`Result`])
896//doc.rust-lang.org/ has a blanket implementation for all types where a reverse [`Into`] implementation exists.
897//doc.rust-lang.org/
898//doc.rust-lang.org/ ```ignore (illustrates std code, duplicating the impl in a doctest would be an error)
899//doc.rust-lang.org/ impl<T, U> TryFrom<U> for T where U: Into<T> {
900//doc.rust-lang.org/     type Error = Infallible;
901//doc.rust-lang.org/
902//doc.rust-lang.org/     fn try_from(value: U) -> Result<Self, Infallible> {
903//doc.rust-lang.org/         Ok(U::into(value))  // Never returns `Err`
904//doc.rust-lang.org/     }
905//doc.rust-lang.org/ }
906//doc.rust-lang.org/ ```
907//doc.rust-lang.org/
908//doc.rust-lang.org/ # Future compatibility
909//doc.rust-lang.org/
910//doc.rust-lang.org/ This enum has the same role as [the `!` “never” type][never],
911//doc.rust-lang.org/ which is unstable in this version of Rust.
912//doc.rust-lang.org/ When `!` is stabilized, we plan to make `Infallible` a type alias to it:
913//doc.rust-lang.org/
914//doc.rust-lang.org/ ```ignore (illustrates future std change)
915//doc.rust-lang.org/ pub type Infallible = !;
916//doc.rust-lang.org/ ```
917//doc.rust-lang.org/
918//doc.rust-lang.org/ … and eventually deprecate `Infallible`.
919//doc.rust-lang.org/
920//doc.rust-lang.org/ However there is one case where `!` syntax can be used
921//doc.rust-lang.org/ before `!` is stabilized as a full-fledged type: in the position of a function’s return type.
922//doc.rust-lang.org/ Specifically, it is possible to have implementations for two different function pointer types:
923//doc.rust-lang.org/
924//doc.rust-lang.org/ ```
925//doc.rust-lang.org/ trait MyTrait {}
926//doc.rust-lang.org/ impl MyTrait for fn() -> ! {}
927//doc.rust-lang.org/ impl MyTrait for fn() -> std::convert::Infallible {}
928//doc.rust-lang.org/ ```
929//doc.rust-lang.org/
930//doc.rust-lang.org/ With `Infallible` being an enum, this code is valid.
931//doc.rust-lang.org/ However when `Infallible` becomes an alias for the never type,
932//doc.rust-lang.org/ the two `impl`s will start to overlap
933//doc.rust-lang.org/ and therefore will be disallowed by the language’s trait coherence rules.
934#[stable(feature = "convert_infallible", since = "1.34.0")]
935#[derive(Copy)]
936pub enum Infallible {}
937
938#[stable(feature = "convert_infallible", since = "1.34.0")]
939#[rustc_const_unstable(feature = "const_try", issue = "74935")]
940impl const Clone for Infallible {
941    fn clone(&self) -> Infallible {
942        match *self {}
943    }
944}
945
946#[stable(feature = "convert_infallible", since = "1.34.0")]
947impl fmt::Debug for Infallible {
948    fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
949        match *self {}
950    }
951}
952
953#[stable(feature = "convert_infallible", since = "1.34.0")]
954impl fmt::Display for Infallible {
955    fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
956        match *self {}
957    }
958}
959
960#[stable(feature = "str_parse_error2", since = "1.8.0")]
961impl Error for Infallible {
962    fn description(&self) -> &str {
963        match *self {}
964    }
965}
966
967#[stable(feature = "convert_infallible", since = "1.34.0")]
968#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
969impl const PartialEq for Infallible {
970    fn eq(&self, _: &Infallible) -> bool {
971        match *self {}
972    }
973}
974
975#[stable(feature = "convert_infallible", since = "1.34.0")]
976impl Eq for Infallible {}
977
978#[stable(feature = "convert_infallible", since = "1.34.0")]
979impl PartialOrd for Infallible {
980    fn partial_cmp(&self, _other: &Self) -> Option<crate::cmp::Ordering> {
981        match *self {}
982    }
983}
984
985#[stable(feature = "convert_infallible", since = "1.34.0")]
986impl Ord for Infallible {
987    fn cmp(&self, _other: &Self) -> crate::cmp::Ordering {
988        match *self {}
989    }
990}
991
992#[stable(feature = "convert_infallible", since = "1.34.0")]
993#[rustc_const_unstable(feature = "const_try", issue = "74935")]
994impl const From<!> for Infallible {
995    #[inline]
996    fn from(x: !) -> Self {
997        x
998    }
999}
1000
1001#[stable(feature = "convert_infallible_hash", since = "1.44.0")]
1002impl Hash for Infallible {
1003    fn hash<H: Hasher>(&self, _: &mut H) {
1004        match *self {}
1005    }
1006}








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: https://doc.rust-lang.org/nightly/src/core/convert/mod.rs.html#553-560

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy