1 //! Traits for conversions between types.
3 //! The traits in this module provide a general way to talk about conversions
4 //! from one type to another. They follow the standard Rust conventions of
5 //! `as`/`into`/`from`.
7 //! Like many traits, these are often used as bounds for generic functions, to
8 //! support arguments of multiple types.
10 //! - Implement the `As*` traits for reference-to-reference conversions
11 //! - Implement the [`Into`] trait when you want to consume the value in the conversion
12 //! - The [`From`] trait is the most flexible, useful for value _and_ reference conversions
13 //! - The [`TryFrom`] and [`TryInto`] traits behave like [`From`] and [`Into`], but allow for the
14 //! conversion to fail
16 //! As a library author, you should prefer implementing [`From<T>`][`From`] or
17 //! [`TryFrom<T>`][`TryFrom`] rather than [`Into<U>`][`Into`] or [`TryInto<U>`][`TryInto`],
18 //! as [`From`] and [`TryFrom`] provide greater flexibility and offer
19 //! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a
20 //! blanket implementation in the standard library. However, there are some cases
21 //! where this is not possible, such as creating conversions into a type defined
22 //! outside your library, so implementing [`Into`] instead of [`From`] is
23 //! sometimes necessary.
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 //! [`Into`]: trait.Into.html
36 //! [`From`]: trait.From.html
37 //! [`TryFrom`]: trait.TryFrom.html
38 //! [`TryInto`]: trait.TryInto.html
39 //! [`AsRef`]: trait.AsRef.html
40 //! [`AsMut`]: trait.AsMut.html
42 #![stable(feature = "rust1", since = "1.0.0")]
44 /// An identity function.
46 /// Two things are important to note about this function:
48 /// - It is not always equivalent to a closure like `|x| x` since the
49 /// closure may coerce `x` into a different type.
51 /// - It moves the input `x` passed to the function.
53 /// While it might seem strange to have a function that just returns back the
54 /// input, there are some interesting uses.
58 /// Using `identity` to do nothing among other interesting functions:
61 /// use std::convert::identity;
63 /// fn manipulation(x: u32) -> u32 {
64 /// // Let's assume that this function does something interesting.
68 /// let _arr = &[identity, manipulation];
71 /// Using `identity` to get a function that changes nothing in a conditional:
74 /// use std::convert::identity;
76 /// # let condition = true;
78 /// # fn manipulation(x: u32) -> u32 { x + 1 }
80 /// let do_stuff = if condition { manipulation } else { identity };
82 /// // do more interesting stuff..
84 /// let _results = do_stuff(42);
87 /// Using `identity` to keep the `Some` variants of an iterator of `Option<T>`:
90 /// use std::convert::identity;
92 /// let iter = vec![Some(1), None, Some(3)].into_iter();
93 /// let filtered = iter.filter_map(identity).collect::<Vec<_>>();
94 /// assert_eq!(vec![1, 3], filtered);
96 #[stable(feature = "convert_id", since = "1.33.0")]
98 pub const fn identity<T>(x: T) -> T { x }
100 /// A cheap reference-to-reference conversion. Used to convert a value to a
101 /// reference value within generic code.
103 /// `AsRef` is very similar to, but serves a slightly different purpose than,
106 /// `AsRef` is to be used when wishing to convert to a reference of another
108 /// `Borrow` is more related to the notion of taking the reference. It is
109 /// useful when wishing to abstract over the type of reference
110 /// (`&T`, `&mut T`) or allow both the referenced and owned type to be treated
111 /// in the same manner.
113 /// The key difference between the two traits is the intention:
115 /// - Use `AsRef` when the goal is to simply convert into a reference
116 /// - Use `Borrow` when the goal is related to writing code that is agnostic to
117 /// the type of borrow and whether it is a reference or value
119 /// [`Borrow`]: ../../std/borrow/trait.Borrow.html
121 /// **Note: this trait must not fail**. If the conversion can fail, use a
122 /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
124 /// [`Option<T>`]: ../../std/option/enum.Option.html
125 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
127 /// # Generic Implementations
129 /// - `AsRef` auto-dereferences if the inner type is a reference or a mutable
130 /// reference (e.g.: `foo.as_ref()` will work the same if `foo` has type
131 /// `&mut Foo` or `&&mut Foo`)
135 /// Both [`String`] and `&str` implement `AsRef<str>`:
137 /// [`String`]: ../../std/string/struct.String.html
140 /// fn is_hello<T: AsRef<str>>(s: T) {
141 /// assert_eq!("hello", s.as_ref());
147 /// let s = "hello".to_string();
151 #[stable(feature = "rust1", since = "1.0.0")]
152 pub trait AsRef<T: ?Sized> {
153 /// Performs the conversion.
154 #[stable(feature = "rust1", since = "1.0.0")]
155 fn as_ref(&self) -> &T;
158 /// A cheap, mutable reference-to-mutable reference conversion.
160 /// This trait is similar to `AsRef` but used for converting between mutable
163 /// **Note: this trait must not fail**. If the conversion can fail, use a
164 /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
166 /// [`Option<T>`]: ../../std/option/enum.Option.html
167 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
169 /// # Generic Implementations
171 /// - `AsMut` auto-dereferences if the inner type is a mutable reference
172 /// (e.g.: `foo.as_mut()` will work the same if `foo` has type `&mut Foo`
173 /// or `&mut &mut Foo`)
177 /// [`Box<T>`] implements `AsMut<T>`:
179 /// [`Box<T>`]: ../../std/boxed/struct.Box.html
182 /// fn add_one<T: AsMut<u64>>(num: &mut T) {
183 /// *num.as_mut() += 1;
186 /// let mut boxed_num = Box::new(0);
187 /// add_one(&mut boxed_num);
188 /// assert_eq!(*boxed_num, 1);
192 #[stable(feature = "rust1", since = "1.0.0")]
193 pub trait AsMut<T: ?Sized> {
194 /// Performs the conversion.
195 #[stable(feature = "rust1", since = "1.0.0")]
196 fn as_mut(&mut self) -> &mut T;
199 /// A conversion that consumes `self`, which may or may not be expensive. The
200 /// reciprocal of [`From`][From].
202 /// **Note: this trait must not fail**. If the conversion can fail, use
203 /// [`TryInto`] or a dedicated method which returns an [`Option<T>`] or a
204 /// [`Result<T, E>`].
206 /// Library authors should not directly implement this trait, but should prefer
207 /// implementing the [`From`][From] trait, which offers greater flexibility and
208 /// provides an equivalent `Into` implementation for free, thanks to a blanket
209 /// implementation in the standard library.
211 /// # Generic Implementations
213 /// - [`From<T>`][From]` for U` implies `Into<U> for T`
214 /// - [`into`] is reflexive, which means that `Into<T> for T` is implemented
216 /// # Implementing `Into`
218 /// There is one exception to implementing `Into`, and it's kind of esoteric.
219 /// If the destination type is not part of the current crate, and it uses a
220 /// generic variable, then you can't implement `From` directly. For example,
224 /// struct Wrapper<T>(Vec<T>);
225 /// impl<T> From<Wrapper<T>> for Vec<T> {
226 /// fn from(w: Wrapper<T>) -> Vec<T> {
232 /// To fix this, you can implement `Into` directly:
235 /// struct Wrapper<T>(Vec<T>);
236 /// impl<T> Into<Vec<T>> for Wrapper<T> {
237 /// fn into(self) -> Vec<T> {
243 /// This won't always allow the conversion: for example, `try!` and `?`
244 /// always use `From`. However, in most cases, people use `Into` to do the
245 /// conversions, and this will allow that.
247 /// In almost all cases, you should try to implement `From`, then fall back
248 /// to `Into` if `From` can't be implemented.
252 /// [`String`] implements `Into<Vec<u8>>`:
255 /// fn is_hello<T: Into<Vec<u8>>>(s: T) {
256 /// let bytes = b"hello".to_vec();
257 /// assert_eq!(bytes, s.into());
260 /// let s = "hello".to_string();
264 /// [`TryInto`]: trait.TryInto.html
265 /// [`Option<T>`]: ../../std/option/enum.Option.html
266 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
267 /// [`String`]: ../../std/string/struct.String.html
268 /// [From]: trait.From.html
269 /// [`into`]: trait.Into.html#tymethod.into
270 #[stable(feature = "rust1", since = "1.0.0")]
271 pub trait Into<T>: Sized {
272 /// Performs the conversion.
273 #[stable(feature = "rust1", since = "1.0.0")]
277 /// Simple and safe type conversions in to `Self`. It is the reciprocal of
280 /// This trait is useful when performing error handling as described by
281 /// [the book][book] and is closely related to the `?` operator.
283 /// When constructing a function that is capable of failing the return type
284 /// will generally be of the form `Result<T, E>`.
286 /// The `From` trait allows for simplification of error handling by providing a
287 /// means of returning a single error type that encapsulates numerous possible
288 /// erroneous situations.
290 /// This trait is not limited to error handling, rather the general case for
291 /// this trait would be in any type conversions to have an explicit definition
292 /// of how they are performed.
294 /// **Note: this trait must not fail**. If the conversion can fail, use
295 /// [`TryFrom`] or a dedicated method which returns an [`Option<T>`] or a
296 /// [`Result<T, E>`].
298 /// # Generic Implementations
300 /// - `From<T> for U` implies [`Into<U>`]` for T`
301 /// - [`from`] is reflexive, which means that `From<T> for T` is implemented
305 /// [`String`] implements `From<&str>`:
308 /// let string = "hello".to_string();
309 /// let other_string = String::from("hello");
311 /// assert_eq!(string, other_string);
314 /// An example usage for error handling:
322 /// IoError(io::Error),
323 /// ParseError(num::ParseIntError),
326 /// impl From<io::Error> for CliError {
327 /// fn from(error: io::Error) -> Self {
328 /// CliError::IoError(error)
332 /// impl From<num::ParseIntError> for CliError {
333 /// fn from(error: num::ParseIntError) -> Self {
334 /// CliError::ParseError(error)
338 /// fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
339 /// let mut contents = fs::read_to_string(&file_name)?;
340 /// let num: i32 = contents.trim().parse()?;
345 /// [`TryFrom`]: trait.TryFrom.html
346 /// [`Option<T>`]: ../../std/option/enum.Option.html
347 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
348 /// [`String`]: ../../std/string/struct.String.html
349 /// [`Into<U>`]: trait.Into.html
350 /// [`from`]: trait.From.html#tymethod.from
351 /// [book]: ../../book/ch09-00-error-handling.html
352 #[stable(feature = "rust1", since = "1.0.0")]
353 pub trait From<T>: Sized {
354 /// Performs the conversion.
355 #[stable(feature = "rust1", since = "1.0.0")]
356 fn from(_: T) -> Self;
359 /// An attempted conversion that consumes `self`, which may or may not be
362 /// Library authors should not directly implement this trait, but should prefer
363 /// implementing the [`TryFrom`] trait, which offers greater flexibility and
364 /// provides an equivalent `TryInto` implementation for free, thanks to a
365 /// blanket implementation in the standard library. For more information on this,
366 /// see the documentation for [`Into`].
368 /// [`TryFrom`]: trait.TryFrom.html
369 /// [`Into`]: trait.Into.html
370 #[unstable(feature = "try_from", issue = "33417")]
371 pub trait TryInto<T>: Sized {
372 /// The type returned in the event of a conversion error.
375 /// Performs the conversion.
376 fn try_into(self) -> Result<T, Self::Error>;
379 /// Attempt to construct `Self` via a conversion.
380 #[unstable(feature = "try_from", issue = "33417")]
381 pub trait TryFrom<T>: Sized {
382 /// The type returned in the event of a conversion error.
385 /// Performs the conversion.
386 fn try_from(value: T) -> Result<Self, Self::Error>;
389 ////////////////////////////////////////////////////////////////////////////////
391 ////////////////////////////////////////////////////////////////////////////////
394 #[stable(feature = "rust1", since = "1.0.0")]
395 impl<T: ?Sized, U: ?Sized> AsRef<U> for &T where T: AsRef<U>
397 fn as_ref(&self) -> &U {
398 <T as AsRef<U>>::as_ref(*self)
402 // As lifts over &mut
403 #[stable(feature = "rust1", since = "1.0.0")]
404 impl<T: ?Sized, U: ?Sized> AsRef<U> for &mut T where T: AsRef<U>
406 fn as_ref(&self) -> &U {
407 <T as AsRef<U>>::as_ref(*self)
411 // FIXME (#45742): replace the above impls for &/&mut with the following more general one:
412 // // As lifts over Deref
413 // impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
414 // fn as_ref(&self) -> &U {
415 // self.deref().as_ref()
419 // AsMut lifts over &mut
420 #[stable(feature = "rust1", since = "1.0.0")]
421 impl<T: ?Sized, U: ?Sized> AsMut<U> for &mut T where T: AsMut<U>
423 fn as_mut(&mut self) -> &mut U {
428 // FIXME (#45742): replace the above impl for &mut with the following more general one:
429 // // AsMut lifts over DerefMut
430 // impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
431 // fn as_mut(&mut self) -> &mut U {
432 // self.deref_mut().as_mut()
437 #[stable(feature = "rust1", since = "1.0.0")]
438 impl<T, U> Into<U> for T where U: From<T>
445 // From (and thus Into) is reflexive
446 #[stable(feature = "rust1", since = "1.0.0")]
447 impl<T> From<T> for T {
448 fn from(t: T) -> T { t }
452 // TryFrom implies TryInto
453 #[unstable(feature = "try_from", issue = "33417")]
454 impl<T, U> TryInto<U> for T where U: TryFrom<T>
456 type Error = U::Error;
458 fn try_into(self) -> Result<U, U::Error> {
463 // Infallible conversions are semantically equivalent to fallible conversions
464 // with an uninhabited error type.
465 #[unstable(feature = "try_from", issue = "33417")]
466 impl<T, U> TryFrom<U> for T where U: Into<T> {
469 fn try_from(value: U) -> Result<Self, Self::Error> {
474 ////////////////////////////////////////////////////////////////////////////////
476 ////////////////////////////////////////////////////////////////////////////////
478 #[stable(feature = "rust1", since = "1.0.0")]
479 impl<T> AsRef<[T]> for [T] {
480 fn as_ref(&self) -> &[T] {
485 #[stable(feature = "rust1", since = "1.0.0")]
486 impl<T> AsMut<[T]> for [T] {
487 fn as_mut(&mut self) -> &mut [T] {
492 #[stable(feature = "rust1", since = "1.0.0")]
493 impl AsRef<str> for str {
495 fn as_ref(&self) -> &str {