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>` or `TryFrom<T>` rather than
27 //! `Into<U>` or `TryInto<U>`, as `From` and `TryFrom` provide greater flexibility and offer
28 //! equivalent `Into` or `TryInto` implementations for free, thanks to a blanket implementation
29 //! in the standard library.
33 //! - `AsRef` and `AsMut` auto-dereference if the inner type is a reference
34 //! - `From<U> for T` implies `Into<T> for U`
35 //! - `TryFrom<U> for T` implies `TryInto<T> for U`
36 //! - `From` and `Into` are reflexive, which means that all types can `into()`
37 //! themselves and `from()` themselves
39 //! See each trait for usage examples.
41 #![stable(feature = "rust1", since = "1.0.0")]
43 /// A cheap, reference-to-reference conversion.
45 /// `AsRef` is very similar to, but different than, [`Borrow`]. See
46 /// [the book][book] for more.
48 /// [book]: ../../book/borrow-and-asref.html
49 /// [`Borrow`]: ../../std/borrow/trait.Borrow.html
51 /// **Note: this trait must not fail**. If the conversion can fail, use a dedicated method which
52 /// returns an [`Option<T>`] or a [`Result<T, E>`].
54 /// [`Option<T>`]: ../../std/option/enum.Option.html
55 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
59 /// Both [`String`] and `&str` implement `AsRef<str>`:
61 /// [`String`]: ../../std/string/struct.String.html
64 /// fn is_hello<T: AsRef<str>>(s: T) {
65 /// assert_eq!("hello", s.as_ref());
71 /// let s = "hello".to_string();
77 /// - `AsRef` auto-dereferences if the inner type is a reference or a mutable
78 /// reference (e.g.: `foo.as_ref()` will work the same if `foo` has type `&mut Foo` or `&&mut Foo`)
80 #[stable(feature = "rust1", since = "1.0.0")]
81 pub trait AsRef<T: ?Sized> {
82 /// Performs the conversion.
83 #[stable(feature = "rust1", since = "1.0.0")]
84 fn as_ref(&self) -> &T;
87 /// A cheap, mutable reference-to-mutable reference conversion.
89 /// **Note: this trait must not fail**. If the conversion can fail, use a dedicated method which
90 /// returns an [`Option<T>`] or a [`Result<T, E>`].
92 /// [`Option<T>`]: ../../std/option/enum.Option.html
93 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
97 /// [`Box<T>`] implements `AsMut<T>`:
99 /// [`Box<T>`]: ../../std/boxed/struct.Box.html
102 /// fn add_one<T: AsMut<u64>>(num: &mut T) {
103 /// *num.as_mut() += 1;
106 /// let mut boxed_num = Box::new(0);
107 /// add_one(&mut boxed_num);
108 /// assert_eq!(*boxed_num, 1);
113 /// - `AsMut` auto-dereferences if the inner type is a reference or a mutable
114 /// reference (e.g.: `foo.as_ref()` will work the same if `foo` has type `&mut Foo` or `&&mut Foo`)
116 #[stable(feature = "rust1", since = "1.0.0")]
117 pub trait AsMut<T: ?Sized> {
118 /// Performs the conversion.
119 #[stable(feature = "rust1", since = "1.0.0")]
120 fn as_mut(&mut self) -> &mut T;
123 /// A conversion that consumes `self`, which may or may not be expensive.
125 /// **Note: this trait must not fail**. If the conversion can fail, use [`TryInto`] or a dedicated
126 /// method which returns an [`Option<T>`] or a [`Result<T, E>`].
128 /// Library authors should not directly implement this trait, but should prefer implementing
129 /// the [`From`][From] trait, which offers greater flexibility and provides an equivalent `Into`
130 /// implementation for free, thanks to a blanket implementation in the standard library.
134 /// [`String`] implements `Into<Vec<u8>>`:
137 /// fn is_hello<T: Into<Vec<u8>>>(s: T) {
138 /// let bytes = b"hello".to_vec();
139 /// assert_eq!(bytes, s.into());
142 /// let s = "hello".to_string();
148 /// - `[From<T>][From] for U` implies `Into<U> for T`
149 /// - [`into()`] is reflexive, which means that `Into<T> for T` is implemented
151 /// [`TryInto`]: trait.TryInto.html
152 /// [`Option<T>`]: ../../std/option/enum.Option.html
153 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
154 /// [`String`]: ../../std/string/struct.String.html
155 /// [From]: trait.From.html
156 /// [`into()`]: trait.Into.html#tymethod.into
157 #[stable(feature = "rust1", since = "1.0.0")]
158 pub trait Into<T>: Sized {
159 /// Performs the conversion.
160 #[stable(feature = "rust1", since = "1.0.0")]
164 /// Construct `Self` via a conversion.
166 /// **Note: this trait must not fail**. If the conversion can fail, use [`TryFrom`] or a dedicated
167 /// method which returns an [`Option<T>`] or a [`Result<T, E>`].
171 /// [`String`] implements `From<&str>`:
174 /// let string = "hello".to_string();
175 /// let other_string = String::from("hello");
177 /// assert_eq!(string, other_string);
181 /// - `From<T> for U` implies `[Into<U>] for T`
182 /// - [`from()`] is reflexive, which means that `From<T> for T` is implemented
184 /// [`TryFrom`]: trait.TryFrom.html
185 /// [`Option<T>`]: ../../std/option/enum.Option.html
186 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
187 /// [`String`]: ../../std/string/struct.String.html
188 /// [Into<U>]: trait.Into.html
189 /// [`from()`]: trait.From.html#tymethod.from
190 #[stable(feature = "rust1", since = "1.0.0")]
191 pub trait From<T>: Sized {
192 /// Performs the conversion.
193 #[stable(feature = "rust1", since = "1.0.0")]
197 /// An attempted conversion that consumes `self`, which may or may not be expensive.
199 /// Library authors should not directly implement this trait, but should prefer implementing
200 /// the [`TryFrom`] trait, which offers greater flexibility and provides an equivalent `TryInto`
201 /// implementation for free, thanks to a blanket implementation in the standard library.
203 /// [`TryFrom`]: trait.TryFrom.html
204 #[unstable(feature = "try_from", issue = "33417")]
205 pub trait TryInto<T>: Sized {
206 /// The type returned in the event of a conversion error.
209 /// Performs the conversion.
210 fn try_into(self) -> Result<T, Self::Err>;
213 /// Attempt to construct `Self` via a conversion.
214 #[unstable(feature = "try_from", issue = "33417")]
215 pub trait TryFrom<T>: Sized {
216 /// The type returned in the event of a conversion error.
219 /// Performs the conversion.
220 fn try_from(T) -> Result<Self, Self::Err>;
223 ////////////////////////////////////////////////////////////////////////////////
225 ////////////////////////////////////////////////////////////////////////////////
228 #[stable(feature = "rust1", since = "1.0.0")]
229 impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a T where T: AsRef<U> {
230 fn as_ref(&self) -> &U {
231 <T as AsRef<U>>::as_ref(*self)
235 // As lifts over &mut
236 #[stable(feature = "rust1", since = "1.0.0")]
237 impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U> {
238 fn as_ref(&self) -> &U {
239 <T as AsRef<U>>::as_ref(*self)
243 // FIXME (#23442): replace the above impls for &/&mut with the following more general one:
244 // // As lifts over Deref
245 // impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
246 // fn as_ref(&self) -> &U {
247 // self.deref().as_ref()
251 // AsMut lifts over &mut
252 #[stable(feature = "rust1", since = "1.0.0")]
253 impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U> {
254 fn as_mut(&mut self) -> &mut U {
259 // FIXME (#23442): replace the above impl for &mut with the following more general one:
260 // // AsMut lifts over DerefMut
261 // impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
262 // fn as_mut(&mut self) -> &mut U {
263 // self.deref_mut().as_mut()
268 #[stable(feature = "rust1", since = "1.0.0")]
269 impl<T, U> Into<U> for T where U: From<T> {
275 // From (and thus Into) is reflexive
276 #[stable(feature = "rust1", since = "1.0.0")]
277 impl<T> From<T> for T {
278 fn from(t: T) -> T { t }
282 // TryFrom implies TryInto
283 #[unstable(feature = "try_from", issue = "33417")]
284 impl<T, U> TryInto<U> for T where U: TryFrom<T> {
287 fn try_into(self) -> Result<U, U::Err> {
292 ////////////////////////////////////////////////////////////////////////////////
294 ////////////////////////////////////////////////////////////////////////////////
296 #[stable(feature = "rust1", since = "1.0.0")]
297 impl<T> AsRef<[T]> for [T] {
298 fn as_ref(&self) -> &[T] {
303 #[stable(feature = "rust1", since = "1.0.0")]
304 impl<T> AsMut<[T]> for [T] {
305 fn as_mut(&mut self) -> &mut [T] {
310 #[stable(feature = "rust1", since = "1.0.0")]
311 impl AsRef<str> for str {
313 fn as_ref(&self) -> &str {