1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Traits for conversions between types.
13 //! The traits in this module provide a general way to talk about conversions
14 //! from one type to another. They follow the standard Rust conventions of
15 //! `as`/`into`/`from`.
17 //! Like many traits, these are often used as bounds for generic functions, to
18 //! support arguments of multiple types.
20 //! - Implement the `As*` traits for reference-to-reference conversions
21 //! - Implement the [`Into`] trait when you want to consume the value in the conversion
22 //! - The [`From`] trait is the most flexible, useful for value _and_ reference conversions
23 //! - The [`TryFrom`] and [`TryInto`] traits behave like [`From`] and [`Into`], but allow for the
24 //! conversion to fail
26 //! As a library author, you should prefer implementing [`From<T>`][`From`] or
27 //! [`TryFrom<T>`][`TryFrom`] rather than [`Into<U>`][`Into`] or [`TryInto<U>`][`TryInto`],
28 //! as [`From`] and [`TryFrom`] provide greater flexibility and offer
29 //! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a
30 //! blanket implementation in the standard library.
32 //! # Generic Implementations
34 //! - [`AsRef`] and [`AsMut`] auto-dereference if the inner type is a reference
35 //! - [`From`]`<U> for T` implies [`Into`]`<T> for U`
36 //! - [`TryFrom`]`<U> for T` implies [`TryInto`]`<T> for U`
37 //! - [`From`] and [`Into`] are reflexive, which means that all types can
38 //! `into` themselves and `from` themselves
40 //! See each trait for usage examples.
42 //! [`Into`]: trait.Into.html
43 //! [`From`]: trait.From.html
44 //! [`TryFrom`]: trait.TryFrom.html
45 //! [`TryInto`]: trait.TryInto.html
46 //! [`AsRef`]: trait.AsRef.html
47 //! [`AsMut`]: trait.AsMut.html
49 #![stable(feature = "rust1", since = "1.0.0")]
53 /// A cheap reference-to-reference conversion. Used to convert a value to a
54 /// reference value within generic code.
56 /// `AsRef` is very similar to, but serves a slightly different purpose than,
59 /// `AsRef` is to be used when wishing to convert to a reference of another
61 /// `Borrow` is more related to the notion of taking the reference. It is
62 /// useful when wishing to abstract over the type of reference
63 /// (`&T`, `&mut T`) or allow both the referenced and owned type to be treated
64 /// in the same manner.
66 /// The key difference between the two traits is the intention:
68 /// - Use `AsRef` when goal is to simply convert into a reference
69 /// - Use `Borrow` when goal is related to writing code that is agnostic to the
70 /// type of borrow and if is reference or value
72 /// See [the book][book] for a more detailed comparison.
74 /// [book]: ../../book/borrow-and-asref.html
75 /// [`Borrow`]: ../../std/borrow/trait.Borrow.html
77 /// **Note: this trait must not fail**. If the conversion can fail, use a
78 /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
80 /// [`Option<T>`]: ../../std/option/enum.Option.html
81 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
83 /// # Generic Implementations
85 /// - `AsRef` auto-dereferences if the inner type is a reference or a mutable
86 /// reference (e.g.: `foo.as_ref()` will work the same if `foo` has type
87 /// `&mut Foo` or `&&mut Foo`)
91 /// Both [`String`] and `&str` implement `AsRef<str>`:
93 /// [`String`]: ../../std/string/struct.String.html
96 /// fn is_hello<T: AsRef<str>>(s: T) {
97 /// assert_eq!("hello", s.as_ref());
103 /// let s = "hello".to_string();
107 #[stable(feature = "rust1", since = "1.0.0")]
108 pub trait AsRef<T: ?Sized> {
109 /// Performs the conversion.
110 #[stable(feature = "rust1", since = "1.0.0")]
111 fn as_ref(&self) -> &T;
114 /// A cheap, mutable reference-to-mutable reference conversion.
116 /// This trait is similar to `AsRef` but used for converting between mutable
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 /// [`Option<T>`]: ../../std/option/enum.Option.html
123 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
125 /// # Generic Implementations
127 /// - `AsMut` auto-dereferences if the inner type is a reference or a mutable
128 /// reference (e.g.: `foo.as_ref()` will work the same if `foo` has type
129 /// `&mut Foo` or `&&mut Foo`)
133 /// [`Box<T>`] implements `AsMut<T>`:
135 /// [`Box<T>`]: ../../std/boxed/struct.Box.html
138 /// fn add_one<T: AsMut<u64>>(num: &mut T) {
139 /// *num.as_mut() += 1;
142 /// let mut boxed_num = Box::new(0);
143 /// add_one(&mut boxed_num);
144 /// assert_eq!(*boxed_num, 1);
148 #[stable(feature = "rust1", since = "1.0.0")]
149 pub trait AsMut<T: ?Sized> {
150 /// Performs the conversion.
151 #[stable(feature = "rust1", since = "1.0.0")]
152 fn as_mut(&mut self) -> &mut T;
155 /// A conversion that consumes `self`, which may or may not be expensive. The
156 /// reciprocal of [`From`][From].
158 /// **Note: this trait must not fail**. If the conversion can fail, use
159 /// [`TryInto`] or a dedicated method which returns an [`Option<T>`] or a
160 /// [`Result<T, E>`].
162 /// Library authors should not directly implement this trait, but should prefer
163 /// implementing the [`From`][From] trait, which offers greater flexibility and
164 /// provides an equivalent `Into` implementation for free, thanks to a blanket
165 /// implementation in the standard library.
167 /// # Generic Implementations
169 /// - [`From<T>`][From]` for U` implies `Into<U> for T`
170 /// - [`into`] is reflexive, which means that `Into<T> for T` is implemented
174 /// [`String`] implements `Into<Vec<u8>>`:
177 /// fn is_hello<T: Into<Vec<u8>>>(s: T) {
178 /// let bytes = b"hello".to_vec();
179 /// assert_eq!(bytes, s.into());
182 /// let s = "hello".to_string();
186 /// [`TryInto`]: trait.TryInto.html
187 /// [`Option<T>`]: ../../std/option/enum.Option.html
188 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
189 /// [`String`]: ../../std/string/struct.String.html
190 /// [From]: trait.From.html
191 /// [`into`]: trait.Into.html#tymethod.into
192 #[stable(feature = "rust1", since = "1.0.0")]
193 pub trait Into<T>: Sized {
194 /// Performs the conversion.
195 #[stable(feature = "rust1", since = "1.0.0")]
199 /// Simple and safe type conversions in to `Self`. It is the reciprocal of
202 /// This trait is useful when performing error handling as described by
203 /// [the book][book] and is closely related to the `?` operator.
205 /// When constructing a function that is capable of failing the return type
206 /// will generally be of the form `Result<T, E>`.
208 /// The `From` trait allows for simplification of error handling by providing a
209 /// means of returning a single error type that encapsulates numerous possible
210 /// erroneous situations.
212 /// This trait is not limited to error handling, rather the general case for
213 /// this trait would be in any type conversions to have an explicit definition
214 /// of how they are performed.
216 /// **Note: this trait must not fail**. If the conversion can fail, use
217 /// [`TryFrom`] or a dedicated method which returns an [`Option<T>`] or a
218 /// [`Result<T, E>`].
220 /// # Generic Implementations
222 /// - `From<T> for U` implies [`Into<U>`]` for T`
223 /// - [`from`] is reflexive, which means that `From<T> for T` is implemented
227 /// [`String`] implements `From<&str>`:
230 /// let string = "hello".to_string();
231 /// let other_string = String::from("hello");
233 /// assert_eq!(string, other_string);
236 /// An example usage for error handling:
239 /// use std::io::{self, Read};
243 /// IoError(io::Error),
244 /// ParseError(num::ParseIntError),
247 /// impl From<io::Error> for CliError {
248 /// fn from(error: io::Error) -> Self {
249 /// CliError::IoError(error)
253 /// impl From<num::ParseIntError> for CliError {
254 /// fn from(error: num::ParseIntError) -> Self {
255 /// CliError::ParseError(error)
259 /// fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
260 /// let mut file = std::fs::File::open("test")?;
261 /// let mut contents = String::new();
262 /// file.read_to_string(&mut contents)?;
263 /// let num: i32 = contents.trim().parse()?;
268 /// [`TryFrom`]: trait.TryFrom.html
269 /// [`Option<T>`]: ../../std/option/enum.Option.html
270 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
271 /// [`String`]: ../../std/string/struct.String.html
272 /// [`Into<U>`]: trait.Into.html
273 /// [`from`]: trait.From.html#tymethod.from
274 /// [book]: ../../book/error-handling.html
275 #[stable(feature = "rust1", since = "1.0.0")]
276 pub trait From<T>: Sized {
277 /// Performs the conversion.
278 #[stable(feature = "rust1", since = "1.0.0")]
282 /// An attempted conversion that consumes `self`, which may or may not be
285 /// Library authors should not directly implement this trait, but should prefer
286 /// implementing the [`TryFrom`] trait, which offers greater flexibility and
287 /// provides an equivalent `TryInto` implementation for free, thanks to a
288 /// blanket implementation in the standard library.
290 /// [`TryFrom`]: trait.TryFrom.html
291 #[unstable(feature = "try_from", issue = "33417")]
292 pub trait TryInto<T>: Sized {
293 /// The type returned in the event of a conversion error.
296 /// Performs the conversion.
297 fn try_into(self) -> Result<T, Self::Error>;
300 /// Attempt to construct `Self` via a conversion.
301 #[unstable(feature = "try_from", issue = "33417")]
302 pub trait TryFrom<T>: Sized {
303 /// The type returned in the event of a conversion error.
306 /// Performs the conversion.
307 fn try_from(value: T) -> Result<Self, Self::Error>;
310 ////////////////////////////////////////////////////////////////////////////////
312 ////////////////////////////////////////////////////////////////////////////////
315 #[stable(feature = "rust1", since = "1.0.0")]
316 impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a T where T: AsRef<U>
318 fn as_ref(&self) -> &U {
319 <T as AsRef<U>>::as_ref(*self)
323 // As lifts over &mut
324 #[stable(feature = "rust1", since = "1.0.0")]
325 impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U>
327 fn as_ref(&self) -> &U {
328 <T as AsRef<U>>::as_ref(*self)
332 // FIXME (#23442): replace the above impls for &/&mut with the following more general one:
333 // // As lifts over Deref
334 // impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
335 // fn as_ref(&self) -> &U {
336 // self.deref().as_ref()
340 // AsMut lifts over &mut
341 #[stable(feature = "rust1", since = "1.0.0")]
342 impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U>
344 fn as_mut(&mut self) -> &mut U {
349 // FIXME (#23442): replace the above impl for &mut with the following more general one:
350 // // AsMut lifts over DerefMut
351 // impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
352 // fn as_mut(&mut self) -> &mut U {
353 // self.deref_mut().as_mut()
358 #[stable(feature = "rust1", since = "1.0.0")]
359 impl<T, U> Into<U> for T where U: From<T>
366 // From (and thus Into) is reflexive
367 #[stable(feature = "rust1", since = "1.0.0")]
368 impl<T> From<T> for T {
369 fn from(t: T) -> T { t }
373 // TryFrom implies TryInto
374 #[unstable(feature = "try_from", issue = "33417")]
375 impl<T, U> TryInto<U> for T where U: TryFrom<T>
377 type Error = U::Error;
379 fn try_into(self) -> Result<U, U::Error> {
384 ////////////////////////////////////////////////////////////////////////////////
386 ////////////////////////////////////////////////////////////////////////////////
388 #[stable(feature = "rust1", since = "1.0.0")]
389 impl<T> AsRef<[T]> for [T] {
390 fn as_ref(&self) -> &[T] {
395 #[stable(feature = "rust1", since = "1.0.0")]
396 impl<T> AsMut<[T]> for [T] {
397 fn as_mut(&mut self) -> &mut [T] {
402 #[stable(feature = "rust1", since = "1.0.0")]
403 impl AsRef<str> for str {
405 fn as_ref(&self) -> &str {
410 // FromStr implies TryFrom<&str>
411 #[unstable(feature = "try_from", issue = "33417")]
412 impl<'a, T> TryFrom<&'a str> for T where T: FromStr
414 type Error = <T as FromStr>::Err;
416 fn try_from(s: &'a str) -> Result<T, Self::Error> {