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 //! - Impl the `As*` traits for reference-to-reference conversions
21 //! - Impl 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 blanket implementation
30 //! in the standard library.
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 `into()`
38 //! 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.
55 /// `AsRef` is very similar to, but different than, [`Borrow`]. See
56 /// [the book][book] for more.
58 /// [book]: ../../book/borrow-and-asref.html
59 /// [`Borrow`]: ../../std/borrow/trait.Borrow.html
61 /// **Note: this trait must not fail**. If the conversion can fail, use a dedicated method which
62 /// returns an [`Option<T>`] or a [`Result<T, E>`].
64 /// [`Option<T>`]: ../../std/option/enum.Option.html
65 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
69 /// Both [`String`] and `&str` implement `AsRef<str>`:
71 /// [`String`]: ../../std/string/struct.String.html
74 /// fn is_hello<T: AsRef<str>>(s: T) {
75 /// assert_eq!("hello", s.as_ref());
81 /// let s = "hello".to_string();
87 /// - `AsRef` auto-dereferences if the inner type is a reference or a mutable
88 /// reference (e.g.: `foo.as_ref()` will work the same if `foo` has type `&mut Foo` or `&&mut Foo`)
90 #[stable(feature = "rust1", since = "1.0.0")]
91 pub trait AsRef<T: ?Sized> {
92 /// Performs the conversion.
93 #[stable(feature = "rust1", since = "1.0.0")]
94 fn as_ref(&self) -> &T;
97 /// A cheap, mutable reference-to-mutable reference conversion.
99 /// **Note: this trait must not fail**. If the conversion can fail, use a dedicated method which
100 /// returns an [`Option<T>`] or a [`Result<T, E>`].
102 /// [`Option<T>`]: ../../std/option/enum.Option.html
103 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
107 /// [`Box<T>`] implements `AsMut<T>`:
109 /// [`Box<T>`]: ../../std/boxed/struct.Box.html
112 /// fn add_one<T: AsMut<u64>>(num: &mut T) {
113 /// *num.as_mut() += 1;
116 /// let mut boxed_num = Box::new(0);
117 /// add_one(&mut boxed_num);
118 /// assert_eq!(*boxed_num, 1);
123 /// - `AsMut` auto-dereferences if the inner type is a reference or a mutable
124 /// reference (e.g.: `foo.as_ref()` will work the same if `foo` has type `&mut Foo` or `&&mut Foo`)
126 #[stable(feature = "rust1", since = "1.0.0")]
127 pub trait AsMut<T: ?Sized> {
128 /// Performs the conversion.
129 #[stable(feature = "rust1", since = "1.0.0")]
130 fn as_mut(&mut self) -> &mut T;
133 /// A conversion that consumes `self`, which may or may not be expensive.
135 /// **Note: this trait must not fail**. If the conversion can fail, use [`TryInto`] or a dedicated
136 /// method which returns an [`Option<T>`] or a [`Result<T, E>`].
138 /// Library authors should not directly implement this trait, but should prefer implementing
139 /// the [`From`][From] trait, which offers greater flexibility and provides an equivalent `Into`
140 /// implementation for free, thanks to a blanket implementation in the standard library.
144 /// [`String`] implements `Into<Vec<u8>>`:
147 /// fn is_hello<T: Into<Vec<u8>>>(s: T) {
148 /// let bytes = b"hello".to_vec();
149 /// assert_eq!(bytes, s.into());
152 /// let s = "hello".to_string();
158 /// - [`From<T>`][From]` for U` implies `Into<U> for T`
159 /// - [`into`] is reflexive, which means that `Into<T> for T` is implemented
161 /// [`TryInto`]: trait.TryInto.html
162 /// [`Option<T>`]: ../../std/option/enum.Option.html
163 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
164 /// [`String`]: ../../std/string/struct.String.html
165 /// [From]: trait.From.html
166 /// [`into`]: trait.Into.html#tymethod.into
167 #[stable(feature = "rust1", since = "1.0.0")]
168 pub trait Into<T>: Sized {
169 /// Performs the conversion.
170 #[stable(feature = "rust1", since = "1.0.0")]
174 /// Construct `Self` via a conversion.
176 /// **Note: this trait must not fail**. If the conversion can fail, use [`TryFrom`] or a dedicated
177 /// method which returns an [`Option<T>`] or a [`Result<T, E>`].
181 /// [`String`] implements `From<&str>`:
184 /// let string = "hello".to_string();
185 /// let other_string = String::from("hello");
187 /// assert_eq!(string, other_string);
191 /// - `From<T> for U` implies [`Into<U>`]` for T`
192 /// - [`from`] is reflexive, which means that `From<T> for T` is implemented
194 /// [`TryFrom`]: trait.TryFrom.html
195 /// [`Option<T>`]: ../../std/option/enum.Option.html
196 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
197 /// [`String`]: ../../std/string/struct.String.html
198 /// [`Into<U>`]: trait.Into.html
199 /// [`from`]: trait.From.html#tymethod.from
200 #[stable(feature = "rust1", since = "1.0.0")]
201 pub trait From<T>: Sized {
202 /// Performs the conversion.
203 #[stable(feature = "rust1", since = "1.0.0")]
207 /// An attempted conversion that consumes `self`, which may or may not be expensive.
209 /// Library authors should not directly implement this trait, but should prefer implementing
210 /// the [`TryFrom`] trait, which offers greater flexibility and provides an equivalent `TryInto`
211 /// implementation for free, thanks to a blanket implementation in the standard library.
213 /// [`TryFrom`]: trait.TryFrom.html
214 #[unstable(feature = "try_from", issue = "33417")]
215 pub trait TryInto<T>: Sized {
216 /// The type returned in the event of a conversion error.
219 /// Performs the conversion.
220 fn try_into(self) -> Result<T, Self::Error>;
223 /// Attempt to construct `Self` via a conversion.
224 #[unstable(feature = "try_from", issue = "33417")]
225 pub trait TryFrom<T>: Sized {
226 /// The type returned in the event of a conversion error.
229 /// Performs the conversion.
230 fn try_from(value: T) -> Result<Self, Self::Error>;
233 ////////////////////////////////////////////////////////////////////////////////
235 ////////////////////////////////////////////////////////////////////////////////
238 #[stable(feature = "rust1", since = "1.0.0")]
239 impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a T where T: AsRef<U> {
240 fn as_ref(&self) -> &U {
241 <T as AsRef<U>>::as_ref(*self)
245 // As lifts over &mut
246 #[stable(feature = "rust1", since = "1.0.0")]
247 impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U> {
248 fn as_ref(&self) -> &U {
249 <T as AsRef<U>>::as_ref(*self)
253 // FIXME (#23442): replace the above impls for &/&mut with the following more general one:
254 // // As lifts over Deref
255 // impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
256 // fn as_ref(&self) -> &U {
257 // self.deref().as_ref()
261 // AsMut lifts over &mut
262 #[stable(feature = "rust1", since = "1.0.0")]
263 impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U> {
264 fn as_mut(&mut self) -> &mut U {
269 // FIXME (#23442): replace the above impl for &mut with the following more general one:
270 // // AsMut lifts over DerefMut
271 // impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
272 // fn as_mut(&mut self) -> &mut U {
273 // self.deref_mut().as_mut()
278 #[stable(feature = "rust1", since = "1.0.0")]
279 impl<T, U> Into<U> for T where U: From<T> {
285 // From (and thus Into) is reflexive
286 #[stable(feature = "rust1", since = "1.0.0")]
287 impl<T> From<T> for T {
288 fn from(t: T) -> T { t }
292 // TryFrom implies TryInto
293 #[unstable(feature = "try_from", issue = "33417")]
294 impl<T, U> TryInto<U> for T where U: TryFrom<T> {
295 type Error = U::Error;
297 fn try_into(self) -> Result<U, U::Error> {
302 ////////////////////////////////////////////////////////////////////////////////
304 ////////////////////////////////////////////////////////////////////////////////
306 #[stable(feature = "rust1", since = "1.0.0")]
307 impl<T> AsRef<[T]> for [T] {
308 fn as_ref(&self) -> &[T] {
313 #[stable(feature = "rust1", since = "1.0.0")]
314 impl<T> AsMut<[T]> for [T] {
315 fn as_mut(&mut self) -> &mut [T] {
320 #[stable(feature = "rust1", since = "1.0.0")]
321 impl AsRef<str> for str {
323 fn as_ref(&self) -> &str {
328 // FromStr implies TryFrom<&str>
329 #[unstable(feature = "try_from", issue = "33417")]
330 impl<'a, T> TryFrom<&'a str> for T where T: FromStr {
331 type Error = <T as FromStr>::Err;
333 fn try_from(s: &'a str) -> Result<T, Self::Error> {