]>
git.proxmox.com Git - rustc.git/blob - library/core/src/convert/mod.rs
1 //! Traits for conversions between types.
3 //! The traits in this module provide a way to convert from one type to another type.
4 //! Each trait serves a different purpose:
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.
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.
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.
25 //! # Generic Implementations
27 //! - [`AsRef`] and [`AsMut`] auto-dereference if the inner type is a reference
28 //! - [`From`]`<U> for T` implies [`Into`]`<T> for U`
29 //! - [`TryFrom`]`<U> for T` implies [`TryInto`]`<T> for U`
30 //! - [`From`] and [`Into`] are reflexive, which means that all types can
31 //! `into` themselves and `from` themselves
33 //! See each trait for usage examples.
35 #![stable(feature = "rust1", since = "1.0.0")]
38 use crate::hash
::{Hash, Hasher}
;
42 #[unstable(feature = "convert_float_to_int", issue = "67057")]
43 pub use num
::FloatToInt
;
45 /// The identity function.
47 /// Two things are important to note about this function:
49 /// - It is not always equivalent to a closure like `|x| x`, since the
50 /// closure may coerce `x` into a different type.
52 /// - It moves the input `x` passed to the function.
54 /// While it might seem strange to have a function that just returns back the
55 /// input, there are some interesting uses.
59 /// Using `identity` to do nothing in a sequence of other, interesting,
63 /// use std::convert::identity;
65 /// fn manipulation(x: u32) -> u32 {
66 /// // Let's pretend that adding one is an interesting function.
70 /// let _arr = &[identity, manipulation];
73 /// Using `identity` as a "do nothing" base case in a conditional:
76 /// use std::convert::identity;
78 /// # let condition = true;
80 /// # fn manipulation(x: u32) -> u32 { x + 1 }
82 /// let do_stuff = if condition { manipulation } else { identity };
84 /// // Do more interesting stuff...
86 /// let _results = do_stuff(42);
89 /// Using `identity` to keep the `Some` variants of an iterator of `Option<T>`:
92 /// use std::convert::identity;
94 /// let iter = vec![Some(1), None, Some(3)].into_iter();
95 /// let filtered = iter.filter_map(identity).collect::<Vec<_>>();
96 /// assert_eq!(vec![1, 3], filtered);
98 #[stable(feature = "convert_id", since = "1.33.0")]
99 #[rustc_const_stable(feature = "const_identity", since = "1.33.0")]
101 pub const fn identity
<T
>(x
: T
) -> T
{
105 /// Used to do a cheap reference-to-reference conversion.
107 /// This trait is similar to [`AsMut`] which is used for converting between mutable references.
108 /// If you need to do a costly conversion it is better to implement [`From`] with type
109 /// `&T` or write a custom function.
111 /// `AsRef` has the same signature as [`Borrow`], but [`Borrow`] is different in few aspects:
113 /// - Unlike `AsRef`, [`Borrow`] has a blanket impl for any `T`, and can be used to accept either
114 /// a reference or a value.
115 /// - [`Borrow`] also requires that [`Hash`], [`Eq`] and [`Ord`] for borrowed value are
116 /// equivalent to those of the owned value. For this reason, if you want to
117 /// borrow only a single field of a struct you can implement `AsRef`, but not [`Borrow`].
119 /// **Note: This trait must not fail**. If the conversion can fail, use a
120 /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
122 /// # Generic Implementations
124 /// - `AsRef` auto-dereferences if the inner type is a reference or a mutable
125 /// reference (e.g.: `foo.as_ref()` will work the same if `foo` has type
126 /// `&mut Foo` or `&&mut Foo`)
130 /// By using trait bounds we can accept arguments of different types as long as they can be
131 /// converted to the specified type `T`.
133 /// For example: By creating a generic function that takes an `AsRef<str>` we express that we
134 /// want to accept all references that can be converted to [`&str`] as an argument.
135 /// Since both [`String`] and [`&str`] implement `AsRef<str>` we can accept both as input argument.
137 /// [`&str`]: primitive@str
138 /// [`Borrow`]: crate::borrow::Borrow
139 /// [`Eq`]: crate::cmp::Eq
140 /// [`Ord`]: crate::cmp::Ord
141 /// [`String`]: ../../std/string/struct.String.html
144 /// fn is_hello<T: AsRef<str>>(s: T) {
145 /// assert_eq!("hello", s.as_ref());
151 /// let s = "hello".to_string();
154 #[stable(feature = "rust1", since = "1.0.0")]
155 #[cfg_attr(not(test), rustc_diagnostic_item = "AsRef")]
156 pub trait AsRef
<T
: ?Sized
> {
157 /// Performs the conversion.
158 #[stable(feature = "rust1", since = "1.0.0")]
159 fn as_ref(&self) -> &T
;
162 /// Used to do a cheap mutable-to-mutable reference conversion.
164 /// This trait is similar to [`AsRef`] but used for converting between mutable
165 /// references. If you need to do a costly conversion it is better to
166 /// implement [`From`] with type `&mut T` or write a custom function.
168 /// **Note: This trait must not fail**. If the conversion can fail, use a
169 /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
171 /// # Generic Implementations
173 /// - `AsMut` auto-dereferences if the inner type is a mutable reference
174 /// (e.g.: `foo.as_mut()` will work the same if `foo` has type `&mut Foo`
175 /// or `&mut &mut Foo`)
179 /// Using `AsMut` as trait bound for a generic function we can accept all mutable references
180 /// that can be converted to type `&mut T`. Because [`Box<T>`] implements `AsMut<T>` we can
181 /// write a function `add_one` that takes all arguments that can be converted to `&mut u64`.
182 /// Because [`Box<T>`] implements `AsMut<T>`, `add_one` accepts arguments of type
183 /// `&mut Box<u64>` as well:
186 /// fn add_one<T: AsMut<u64>>(num: &mut T) {
187 /// *num.as_mut() += 1;
190 /// let mut boxed_num = Box::new(0);
191 /// add_one(&mut boxed_num);
192 /// assert_eq!(*boxed_num, 1);
195 /// [`Box<T>`]: ../../std/boxed/struct.Box.html
196 #[stable(feature = "rust1", since = "1.0.0")]
197 #[cfg_attr(not(test), rustc_diagnostic_item = "AsMut")]
198 pub trait AsMut
<T
: ?Sized
> {
199 /// Performs the conversion.
200 #[stable(feature = "rust1", since = "1.0.0")]
201 fn as_mut(&mut self) -> &mut T
;
204 /// A value-to-value conversion that consumes the input value. The
205 /// opposite of [`From`].
207 /// One should avoid implementing [`Into`] and implement [`From`] instead.
208 /// Implementing [`From`] automatically provides one with an implementation of [`Into`]
209 /// thanks to the blanket implementation in the standard library.
211 /// Prefer using [`Into`] over [`From`] when specifying trait bounds on a generic function
212 /// to ensure that types that only implement [`Into`] can be used as well.
214 /// **Note: This trait must not fail**. If the conversion can fail, use [`TryInto`].
216 /// # Generic Implementations
218 /// - [`From`]`<T> for U` implies `Into<U> for T`
219 /// - [`Into`] is reflexive, which means that `Into<T> for T` is implemented
221 /// # Implementing [`Into`] for conversions to external types in old versions of Rust
223 /// Prior to Rust 1.41, if the destination type was not part of the current crate
224 /// then you couldn't implement [`From`] directly.
225 /// For example, take this code:
228 /// struct Wrapper<T>(Vec<T>);
229 /// impl<T> From<Wrapper<T>> for Vec<T> {
230 /// fn from(w: Wrapper<T>) -> Vec<T> {
235 /// This will fail to compile in older versions of the language because Rust's orphaning rules
236 /// used to be a little bit more strict. To bypass this, you could implement [`Into`] directly:
239 /// struct Wrapper<T>(Vec<T>);
240 /// impl<T> Into<Vec<T>> for Wrapper<T> {
241 /// fn into(self) -> Vec<T> {
247 /// It is important to understand that [`Into`] does not provide a [`From`] implementation
248 /// (as [`From`] does with [`Into`]). Therefore, you should always try to implement [`From`]
249 /// and then fall back to [`Into`] if [`From`] can't be implemented.
253 /// [`String`] implements [`Into`]`<`[`Vec`]`<`[`u8`]`>>`:
255 /// In order to express that we want a generic function to take all arguments that can be
256 /// converted to a specified type `T`, we can use a trait bound of [`Into`]`<T>`.
257 /// For example: The function `is_hello` takes all arguments that can be converted into a
258 /// [`Vec`]`<`[`u8`]`>`.
261 /// fn is_hello<T: Into<Vec<u8>>>(s: T) {
262 /// let bytes = b"hello".to_vec();
263 /// assert_eq!(bytes, s.into());
266 /// let s = "hello".to_string();
270 /// [`String`]: ../../std/string/struct.String.html
271 /// [`Vec`]: ../../std/vec/struct.Vec.html
272 #[rustc_diagnostic_item = "into_trait"]
273 #[stable(feature = "rust1", since = "1.0.0")]
274 pub trait Into
<T
>: Sized
{
275 /// Performs the conversion.
276 #[stable(feature = "rust1", since = "1.0.0")]
280 /// Used to do value-to-value conversions while consuming the input value. It is the reciprocal of
283 /// One should always prefer implementing `From` over [`Into`]
284 /// because implementing `From` automatically provides one with an implementation of [`Into`]
285 /// thanks to the blanket implementation in the standard library.
287 /// Only implement [`Into`] when targeting a version prior to Rust 1.41 and converting to a type
288 /// outside the current crate.
289 /// `From` was not able to do these types of conversions in earlier versions because of Rust's
291 /// See [`Into`] for more details.
293 /// Prefer using [`Into`] over using `From` when specifying trait bounds on a generic function.
294 /// This way, types that directly implement [`Into`] can be used as arguments as well.
296 /// The `From` is also very useful when performing error handling. When constructing a function
297 /// that is capable of failing, the return type will generally be of the form `Result<T, E>`.
298 /// The `From` trait simplifies error handling by allowing a function to return a single error type
299 /// that encapsulate multiple error types. See the "Examples" section and [the book][book] for more
302 /// **Note: This trait must not fail**. If the conversion can fail, use [`TryFrom`].
304 /// # Generic Implementations
306 /// - `From<T> for U` implies [`Into`]`<U> for T`
307 /// - `From` is reflexive, which means that `From<T> for T` is implemented
311 /// [`String`] implements `From<&str>`:
313 /// An explicit conversion from a `&str` to a String is done as follows:
316 /// let string = "hello".to_string();
317 /// let other_string = String::from("hello");
319 /// assert_eq!(string, other_string);
322 /// While performing error handling it is often useful to implement `From` for your own error type.
323 /// By converting underlying error types to our own custom error type that encapsulates the
324 /// underlying error type, we can return a single error type without losing information on the
325 /// underlying cause. The '?' operator automatically converts the underlying error type to our
326 /// custom error type by calling `Into<CliError>::into` which is automatically provided when
327 /// implementing `From`. The compiler then infers which implementation of `Into` should be used.
335 /// IoError(io::Error),
336 /// ParseError(num::ParseIntError),
339 /// impl From<io::Error> for CliError {
340 /// fn from(error: io::Error) -> Self {
341 /// CliError::IoError(error)
345 /// impl From<num::ParseIntError> for CliError {
346 /// fn from(error: num::ParseIntError) -> Self {
347 /// CliError::ParseError(error)
351 /// fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
352 /// let mut contents = fs::read_to_string(&file_name)?;
353 /// let num: i32 = contents.trim().parse()?;
358 /// [`String`]: ../../std/string/struct.String.html
359 /// [`from`]: From::from
360 /// [book]: ../../book/ch09-00-error-handling.html
361 #[rustc_diagnostic_item = "from_trait"]
362 #[stable(feature = "rust1", since = "1.0.0")]
363 #[rustc_on_unimplemented(on(
364 all(_Self
= "&str", T
= "std::string::String"),
365 note
= "to coerce a `{T}` into a `{Self}`, use `&*` as a prefix",
367 pub trait From
<T
>: Sized
{
368 /// Performs the conversion.
370 #[stable(feature = "rust1", since = "1.0.0")]
371 fn from(_
: T
) -> Self;
374 /// An attempted conversion that consumes `self`, which may or may not be
377 /// Library authors should usually not directly implement this trait,
378 /// but should prefer implementing the [`TryFrom`] trait, which offers
379 /// greater flexibility and provides an equivalent `TryInto`
380 /// implementation for free, thanks to a blanket implementation in the
381 /// standard library. For more information on this, see the
382 /// documentation for [`Into`].
384 /// # Implementing `TryInto`
386 /// This suffers the same restrictions and reasoning as implementing
387 /// [`Into`], see there for details.
388 #[rustc_diagnostic_item = "try_into_trait"]
389 #[stable(feature = "try_from", since = "1.34.0")]
390 pub trait TryInto
<T
>: Sized
{
391 /// The type returned in the event of a conversion error.
392 #[stable(feature = "try_from", since = "1.34.0")]
395 /// Performs the conversion.
396 #[stable(feature = "try_from", since = "1.34.0")]
397 fn try_into(self) -> Result
<T
, Self::Error
>;
400 /// Simple and safe type conversions that may fail in a controlled
401 /// way under some circumstances. It is the reciprocal of [`TryInto`].
403 /// This is useful when you are doing a type conversion that may
404 /// trivially succeed but may also need special handling.
405 /// For example, there is no way to convert an [`i64`] into an [`i32`]
406 /// using the [`From`] trait, because an [`i64`] may contain a value
407 /// that an [`i32`] cannot represent and so the conversion would lose data.
408 /// This might be handled by truncating the [`i64`] to an [`i32`] (essentially
409 /// giving the [`i64`]'s value modulo [`i32::MAX`]) or by simply returning
410 /// [`i32::MAX`], or by some other method. The [`From`] trait is intended
411 /// for perfect conversions, so the `TryFrom` trait informs the
412 /// programmer when a type conversion could go bad and lets them
413 /// decide how to handle it.
415 /// # Generic Implementations
417 /// - `TryFrom<T> for U` implies [`TryInto`]`<U> for T`
418 /// - [`try_from`] is reflexive, which means that `TryFrom<T> for T`
419 /// is implemented and cannot fail -- the associated `Error` type for
420 /// calling `T::try_from()` on a value of type `T` is [`Infallible`].
421 /// When the [`!`] type is stabilized [`Infallible`] and [`!`] will be
424 /// `TryFrom<T>` can be implemented as follows:
427 /// use std::convert::TryFrom;
429 /// struct GreaterThanZero(i32);
431 /// impl TryFrom<i32> for GreaterThanZero {
432 /// type Error = &'static str;
434 /// fn try_from(value: i32) -> Result<Self, Self::Error> {
436 /// Err("GreaterThanZero only accepts value superior than zero!")
438 /// Ok(GreaterThanZero(value))
446 /// As described, [`i32`] implements `TryFrom<`[`i64`]`>`:
449 /// use std::convert::TryFrom;
451 /// let big_number = 1_000_000_000_000i64;
452 /// // Silently truncates `big_number`, requires detecting
453 /// // and handling the truncation after the fact.
454 /// let smaller_number = big_number as i32;
455 /// assert_eq!(smaller_number, -727379968);
457 /// // Returns an error because `big_number` is too big to
458 /// // fit in an `i32`.
459 /// let try_smaller_number = i32::try_from(big_number);
460 /// assert!(try_smaller_number.is_err());
462 /// // Returns `Ok(3)`.
463 /// let try_successful_smaller_number = i32::try_from(3);
464 /// assert!(try_successful_smaller_number.is_ok());
467 /// [`try_from`]: TryFrom::try_from
468 #[rustc_diagnostic_item = "try_from_trait"]
469 #[stable(feature = "try_from", since = "1.34.0")]
470 pub trait TryFrom
<T
>: Sized
{
471 /// The type returned in the event of a conversion error.
472 #[stable(feature = "try_from", since = "1.34.0")]
475 /// Performs the conversion.
476 #[stable(feature = "try_from", since = "1.34.0")]
477 fn try_from(value
: T
) -> Result
<Self, Self::Error
>;
480 ////////////////////////////////////////////////////////////////////////////////
482 ////////////////////////////////////////////////////////////////////////////////
485 #[stable(feature = "rust1", since = "1.0.0")]
486 impl<T
: ?Sized
, U
: ?Sized
> AsRef
<U
> for &T
490 fn as_ref(&self) -> &U
{
491 <T
as AsRef
<U
>>::as_ref(*self)
495 // As lifts over &mut
496 #[stable(feature = "rust1", since = "1.0.0")]
497 impl<T
: ?Sized
, U
: ?Sized
> AsRef
<U
> for &mut T
501 fn as_ref(&self) -> &U
{
502 <T
as AsRef
<U
>>::as_ref(*self)
506 // FIXME (#45742): replace the above impls for &/&mut with the following more general one:
507 // // As lifts over Deref
508 // impl<D: ?Sized + Deref<Target: AsRef<U>>, U: ?Sized> AsRef<U> for D {
509 // fn as_ref(&self) -> &U {
510 // self.deref().as_ref()
514 // AsMut lifts over &mut
515 #[stable(feature = "rust1", since = "1.0.0")]
516 impl<T
: ?Sized
, U
: ?Sized
> AsMut
<U
> for &mut T
520 fn as_mut(&mut self) -> &mut U
{
525 // FIXME (#45742): replace the above impl for &mut with the following more general one:
526 // // AsMut lifts over DerefMut
527 // impl<D: ?Sized + Deref<Target: AsMut<U>>, U: ?Sized> AsMut<U> for D {
528 // fn as_mut(&mut self) -> &mut U {
529 // self.deref_mut().as_mut()
534 #[stable(feature = "rust1", since = "1.0.0")]
535 impl<T
, U
> Into
<U
> for T
544 // From (and thus Into) is reflexive
545 #[stable(feature = "rust1", since = "1.0.0")]
546 impl<T
> From
<T
> for T
{
552 /// **Stability note:** This impl does not yet exist, but we are
553 /// "reserving space" to add it in the future. See
554 /// [rust-lang/rust#64715][#64715] for details.
556 /// [#64715]: https://github.com/rust-lang/rust/issues/64715
557 #[stable(feature = "convert_infallible", since = "1.34.0")]
558 #[allow(unused_attributes)] // FIXME(#58633): do a principled fix instead.
559 #[rustc_reservation_impl = "permitting this impl would forbid us from adding \
560 `impl<T> From<!> for T` later; see rust-lang/rust#64715 for details"]
561 impl<T
> From
<!> for T
{
567 // TryFrom implies TryInto
568 #[stable(feature = "try_from", since = "1.34.0")]
569 impl<T
, U
> TryInto
<U
> for T
573 type Error
= U
::Error
;
575 fn try_into(self) -> Result
<U
, U
::Error
> {
580 // Infallible conversions are semantically equivalent to fallible conversions
581 // with an uninhabited error type.
582 #[stable(feature = "try_from", since = "1.34.0")]
583 impl<T
, U
> TryFrom
<U
> for T
587 type Error
= Infallible
;
589 fn try_from(value
: U
) -> Result
<Self, Self::Error
> {
594 ////////////////////////////////////////////////////////////////////////////////
596 ////////////////////////////////////////////////////////////////////////////////
598 #[stable(feature = "rust1", since = "1.0.0")]
599 impl<T
> AsRef
<[T
]> for [T
] {
600 fn as_ref(&self) -> &[T
] {
605 #[stable(feature = "rust1", since = "1.0.0")]
606 impl<T
> AsMut
<[T
]> for [T
] {
607 fn as_mut(&mut self) -> &mut [T
] {
612 #[stable(feature = "rust1", since = "1.0.0")]
613 impl AsRef
<str> for str {
615 fn as_ref(&self) -> &str {
620 #[stable(feature = "as_mut_str_for_str", since = "1.51.0")]
621 impl AsMut
<str> for str {
623 fn as_mut(&mut self) -> &mut str {
628 ////////////////////////////////////////////////////////////////////////////////
629 // THE NO-ERROR ERROR TYPE
630 ////////////////////////////////////////////////////////////////////////////////
632 /// The error type for errors that can never happen.
634 /// Since this enum has no variant, a value of this type can never actually exist.
635 /// This can be useful for generic APIs that use [`Result`] and parameterize the error type,
636 /// to indicate that the result is always [`Ok`].
638 /// For example, the [`TryFrom`] trait (conversion that returns a [`Result`])
639 /// has a blanket implementation for all types where a reverse [`Into`] implementation exists.
641 /// ```ignore (illustrates std code, duplicating the impl in a doctest would be an error)
642 /// impl<T, U> TryFrom<U> for T where U: Into<T> {
643 /// type Error = Infallible;
645 /// fn try_from(value: U) -> Result<Self, Infallible> {
646 /// Ok(U::into(value)) // Never returns `Err`
651 /// # Future compatibility
653 /// This enum has the same role as [the `!` “never” type][never],
654 /// which is unstable in this version of Rust.
655 /// When `!` is stabilized, we plan to make `Infallible` a type alias to it:
657 /// ```ignore (illustrates future std change)
658 /// pub type Infallible = !;
661 /// … and eventually deprecate `Infallible`.
663 /// However there is one case where `!` syntax can be used
664 /// before `!` is stabilized as a full-fledged type: in the position of a function’s return type.
665 /// Specifically, it is possible implementations for two different function pointer types:
669 /// impl MyTrait for fn() -> ! {}
670 /// impl MyTrait for fn() -> std::convert::Infallible {}
673 /// With `Infallible` being an enum, this code is valid.
674 /// However when `Infallible` becomes an alias for the never type,
675 /// the two `impl`s will start to overlap
676 /// and therefore will be disallowed by the language’s trait coherence rules.
677 #[stable(feature = "convert_infallible", since = "1.34.0")]
679 pub enum Infallible {}
681 #[stable(feature = "convert_infallible", since = "1.34.0")]
682 impl Clone
for Infallible
{
683 fn clone(&self) -> Infallible
{
688 #[stable(feature = "convert_infallible", since = "1.34.0")]
689 impl fmt
::Debug
for Infallible
{
690 fn fmt(&self, _
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
695 #[stable(feature = "convert_infallible", since = "1.34.0")]
696 impl fmt
::Display
for Infallible
{
697 fn fmt(&self, _
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
702 #[stable(feature = "convert_infallible", since = "1.34.0")]
703 impl PartialEq
for Infallible
{
704 fn eq(&self, _
: &Infallible
) -> bool
{
709 #[stable(feature = "convert_infallible", since = "1.34.0")]
710 impl Eq
for Infallible {}
712 #[stable(feature = "convert_infallible", since = "1.34.0")]
713 impl PartialOrd
for Infallible
{
714 fn partial_cmp(&self, _other
: &Self) -> Option
<crate::cmp
::Ordering
> {
719 #[stable(feature = "convert_infallible", since = "1.34.0")]
720 impl Ord
for Infallible
{
721 fn cmp(&self, _other
: &Self) -> crate::cmp
::Ordering
{
726 #[stable(feature = "convert_infallible", since = "1.34.0")]
727 impl From
<!> for Infallible
{
728 fn from(x
: !) -> Self {
733 #[stable(feature = "convert_infallible_hash", since = "1.44.0")]
734 impl Hash
for Infallible
{
735 fn hash
<H
: Hasher
>(&self, _
: &mut H
) {