]> git.lizzy.rs Git - rust.git/blob - src/libcore/convert.rs
Auto merge of #58341 - alexreg:cosmetic-2-doc-comments, r=steveklabnik
[rust.git] / src / libcore / convert.rs
1 //! Traits for conversions between types.
2 //!
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`.
6 //!
7 //! Like many traits, these are often used as bounds for generic functions, to
8 //! support arguments of multiple types.
9 //!
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
15 //!
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.
24 //!
25 //! # Generic Implementations
26 //!
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
32 //!
33 //! See each trait for usage examples.
34 //!
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
41
42 #![stable(feature = "rust1", since = "1.0.0")]
43
44 /// An identity function.
45 ///
46 /// Two things are important to note about this function:
47 ///
48 /// - It is not always equivalent to a closure like `|x| x` since the
49 ///   closure may coerce `x` into a different type.
50 ///
51 /// - It moves the input `x` passed to the function.
52 ///
53 /// While it might seem strange to have a function that just returns back the
54 /// input, there are some interesting uses.
55 ///
56 /// # Examples
57 ///
58 /// Using `identity` to do nothing among other interesting functions:
59 ///
60 /// ```rust
61 /// use std::convert::identity;
62 ///
63 /// fn manipulation(x: u32) -> u32 {
64 ///     // Let's assume that this function does something interesting.
65 ///     x + 1
66 /// }
67 ///
68 /// let _arr = &[identity, manipulation];
69 /// ```
70 ///
71 /// Using `identity` to get a function that changes nothing in a conditional:
72 ///
73 /// ```rust
74 /// use std::convert::identity;
75 ///
76 /// # let condition = true;
77 ///
78 /// # fn manipulation(x: u32) -> u32 { x + 1 }
79 ///
80 /// let do_stuff = if condition { manipulation } else { identity };
81 ///
82 /// // do more interesting stuff..
83 ///
84 /// let _results = do_stuff(42);
85 /// ```
86 ///
87 /// Using `identity` to keep the `Some` variants of an iterator of `Option<T>`:
88 ///
89 /// ```rust
90 /// use std::convert::identity;
91 ///
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);
95 /// ```
96 #[stable(feature = "convert_id", since = "1.33.0")]
97 #[inline]
98 pub const fn identity<T>(x: T) -> T { x }
99
100 /// A cheap reference-to-reference conversion. Used to convert a value to a
101 /// reference value within generic code.
102 ///
103 /// `AsRef` is very similar to, but serves a slightly different purpose than,
104 /// [`Borrow`].
105 ///
106 /// `AsRef` is to be used when wishing to convert to a reference of another
107 /// type.
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.
112 ///
113 /// The key difference between the two traits is the intention:
114 ///
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
118 ///
119 /// See [the book][book] for a more detailed comparison.
120 ///
121 /// [book]: ../../book/first-edition/borrow-and-asref.html
122 /// [`Borrow`]: ../../std/borrow/trait.Borrow.html
123 ///
124 /// **Note: this trait must not fail**. If the conversion can fail, use a
125 /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
126 ///
127 /// [`Option<T>`]: ../../std/option/enum.Option.html
128 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
129 ///
130 /// # Generic Implementations
131 ///
132 /// - `AsRef` auto-dereferences if the inner type is a reference or a mutable
133 ///   reference (e.g.: `foo.as_ref()` will work the same if `foo` has type
134 ///   `&mut Foo` or `&&mut Foo`)
135 ///
136 /// # Examples
137 ///
138 /// Both [`String`] and `&str` implement `AsRef<str>`:
139 ///
140 /// [`String`]: ../../std/string/struct.String.html
141 ///
142 /// ```
143 /// fn is_hello<T: AsRef<str>>(s: T) {
144 ///    assert_eq!("hello", s.as_ref());
145 /// }
146 ///
147 /// let s = "hello";
148 /// is_hello(s);
149 ///
150 /// let s = "hello".to_string();
151 /// is_hello(s);
152 /// ```
153 ///
154 #[stable(feature = "rust1", since = "1.0.0")]
155 pub trait AsRef<T: ?Sized> {
156     /// Performs the conversion.
157     #[stable(feature = "rust1", since = "1.0.0")]
158     fn as_ref(&self) -> &T;
159 }
160
161 /// A cheap, mutable reference-to-mutable reference conversion.
162 ///
163 /// This trait is similar to `AsRef` but used for converting between mutable
164 /// references.
165 ///
166 /// **Note: this trait must not fail**. If the conversion can fail, use a
167 /// dedicated method which returns an [`Option<T>`] or a [`Result<T, E>`].
168 ///
169 /// [`Option<T>`]: ../../std/option/enum.Option.html
170 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
171 ///
172 /// # Generic Implementations
173 ///
174 /// - `AsMut` auto-dereferences if the inner type is a mutable reference
175 ///   (e.g.: `foo.as_mut()` will work the same if `foo` has type `&mut Foo`
176 ///   or `&mut &mut Foo`)
177 ///
178 /// # Examples
179 ///
180 /// [`Box<T>`] implements `AsMut<T>`:
181 ///
182 /// [`Box<T>`]: ../../std/boxed/struct.Box.html
183 ///
184 /// ```
185 /// fn add_one<T: AsMut<u64>>(num: &mut T) {
186 ///     *num.as_mut() += 1;
187 /// }
188 ///
189 /// let mut boxed_num = Box::new(0);
190 /// add_one(&mut boxed_num);
191 /// assert_eq!(*boxed_num, 1);
192 /// ```
193 ///
194 ///
195 #[stable(feature = "rust1", since = "1.0.0")]
196 pub trait AsMut<T: ?Sized> {
197     /// Performs the conversion.
198     #[stable(feature = "rust1", since = "1.0.0")]
199     fn as_mut(&mut self) -> &mut T;
200 }
201
202 /// A conversion that consumes `self`, which may or may not be expensive. The
203 /// reciprocal of [`From`][From].
204 ///
205 /// **Note: this trait must not fail**. If the conversion can fail, use
206 /// [`TryInto`] or a dedicated method which returns an [`Option<T>`] or a
207 /// [`Result<T, E>`].
208 ///
209 /// Library authors should not directly implement this trait, but should prefer
210 /// implementing the [`From`][From] trait, which offers greater flexibility and
211 /// provides an equivalent `Into` implementation for free, thanks to a blanket
212 /// implementation in the standard library.
213 ///
214 /// # Generic Implementations
215 ///
216 /// - [`From<T>`][From]` for U` implies `Into<U> for T`
217 /// - [`into`] is reflexive, which means that `Into<T> for T` is implemented
218 ///
219 /// # Implementing `Into`
220 ///
221 /// There is one exception to implementing `Into`, and it's kind of esoteric.
222 /// If the destination type is not part of the current crate, and it uses a
223 /// generic variable, then you can't implement `From` directly. For example,
224 /// take this crate:
225 ///
226 /// ```compile_fail
227 /// struct Wrapper<T>(Vec<T>);
228 /// impl<T> From<Wrapper<T>> for Vec<T> {
229 ///     fn from(w: Wrapper<T>) -> Vec<T> {
230 ///         w.0
231 ///     }
232 /// }
233 /// ```
234 ///
235 /// To fix this, you can implement `Into` directly:
236 ///
237 /// ```
238 /// struct Wrapper<T>(Vec<T>);
239 /// impl<T> Into<Vec<T>> for Wrapper<T> {
240 ///     fn into(self) -> Vec<T> {
241 ///         self.0
242 ///     }
243 /// }
244 /// ```
245 ///
246 /// This won't always allow the conversion: for example, `try!` and `?`
247 /// always use `From`. However, in most cases, people use `Into` to do the
248 /// conversions, and this will allow that.
249 ///
250 /// In almost all cases, you should try to implement `From`, then fall back
251 /// to `Into` if `From` can't be implemented.
252 ///
253 /// # Examples
254 ///
255 /// [`String`] implements `Into<Vec<u8>>`:
256 ///
257 /// ```
258 /// fn is_hello<T: Into<Vec<u8>>>(s: T) {
259 ///    let bytes = b"hello".to_vec();
260 ///    assert_eq!(bytes, s.into());
261 /// }
262 ///
263 /// let s = "hello".to_string();
264 /// is_hello(s);
265 /// ```
266 ///
267 /// [`TryInto`]: trait.TryInto.html
268 /// [`Option<T>`]: ../../std/option/enum.Option.html
269 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
270 /// [`String`]: ../../std/string/struct.String.html
271 /// [From]: trait.From.html
272 /// [`into`]: trait.Into.html#tymethod.into
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")]
277     fn into(self) -> T;
278 }
279
280 /// Simple and safe type conversions in to `Self`. It is the reciprocal of
281 /// `Into`.
282 ///
283 /// This trait is useful when performing error handling as described by
284 /// [the book][book] and is closely related to the `?` operator.
285 ///
286 /// When constructing a function that is capable of failing the return type
287 /// will generally be of the form `Result<T, E>`.
288 ///
289 /// The `From` trait allows for simplification of error handling by providing a
290 /// means of returning a single error type that encapsulates numerous possible
291 /// erroneous situations.
292 ///
293 /// This trait is not limited to error handling, rather the general case for
294 /// this trait would be in any type conversions to have an explicit definition
295 /// of how they are performed.
296 ///
297 /// **Note: this trait must not fail**. If the conversion can fail, use
298 /// [`TryFrom`] or a dedicated method which returns an [`Option<T>`] or a
299 /// [`Result<T, E>`].
300 ///
301 /// # Generic Implementations
302 ///
303 /// - `From<T> for U` implies [`Into<U>`]` for T`
304 /// - [`from`] is reflexive, which means that `From<T> for T` is implemented
305 ///
306 /// # Examples
307 ///
308 /// [`String`] implements `From<&str>`:
309 ///
310 /// ```
311 /// let string = "hello".to_string();
312 /// let other_string = String::from("hello");
313 ///
314 /// assert_eq!(string, other_string);
315 /// ```
316 ///
317 /// An example usage for error handling:
318 ///
319 /// ```
320 /// use std::fs;
321 /// use std::io;
322 /// use std::num;
323 ///
324 /// enum CliError {
325 ///     IoError(io::Error),
326 ///     ParseError(num::ParseIntError),
327 /// }
328 ///
329 /// impl From<io::Error> for CliError {
330 ///     fn from(error: io::Error) -> Self {
331 ///         CliError::IoError(error)
332 ///     }
333 /// }
334 ///
335 /// impl From<num::ParseIntError> for CliError {
336 ///     fn from(error: num::ParseIntError) -> Self {
337 ///         CliError::ParseError(error)
338 ///     }
339 /// }
340 ///
341 /// fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
342 ///     let mut contents = fs::read_to_string(&file_name)?;
343 ///     let num: i32 = contents.trim().parse()?;
344 ///     Ok(num)
345 /// }
346 /// ```
347 ///
348 /// [`TryFrom`]: trait.TryFrom.html
349 /// [`Option<T>`]: ../../std/option/enum.Option.html
350 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
351 /// [`String`]: ../../std/string/struct.String.html
352 /// [`Into<U>`]: trait.Into.html
353 /// [`from`]: trait.From.html#tymethod.from
354 /// [book]: ../../book/first-edition/error-handling.html
355 #[stable(feature = "rust1", since = "1.0.0")]
356 pub trait From<T>: Sized {
357     /// Performs the conversion.
358     #[stable(feature = "rust1", since = "1.0.0")]
359     fn from(_: T) -> Self;
360 }
361
362 /// An attempted conversion that consumes `self`, which may or may not be
363 /// expensive.
364 ///
365 /// Library authors should not directly implement this trait, but should prefer
366 /// implementing the [`TryFrom`] trait, which offers greater flexibility and
367 /// provides an equivalent `TryInto` implementation for free, thanks to a
368 /// blanket implementation in the standard library. For more information on this,
369 /// see the documentation for [`Into`].
370 ///
371 /// [`TryFrom`]: trait.TryFrom.html
372 /// [`Into`]: trait.Into.html
373 #[unstable(feature = "try_from", issue = "33417")]
374 pub trait TryInto<T>: Sized {
375     /// The type returned in the event of a conversion error.
376     type Error;
377
378     /// Performs the conversion.
379     fn try_into(self) -> Result<T, Self::Error>;
380 }
381
382 /// Attempt to construct `Self` via a conversion.
383 #[unstable(feature = "try_from", issue = "33417")]
384 pub trait TryFrom<T>: Sized {
385     /// The type returned in the event of a conversion error.
386     type Error;
387
388     /// Performs the conversion.
389     fn try_from(value: T) -> Result<Self, Self::Error>;
390 }
391
392 ////////////////////////////////////////////////////////////////////////////////
393 // GENERIC IMPLS
394 ////////////////////////////////////////////////////////////////////////////////
395
396 // As lifts over &
397 #[stable(feature = "rust1", since = "1.0.0")]
398 impl<T: ?Sized, U: ?Sized> AsRef<U> for &T where T: AsRef<U>
399 {
400     fn as_ref(&self) -> &U {
401         <T as AsRef<U>>::as_ref(*self)
402     }
403 }
404
405 // As lifts over &mut
406 #[stable(feature = "rust1", since = "1.0.0")]
407 impl<T: ?Sized, U: ?Sized> AsRef<U> for &mut T where T: AsRef<U>
408 {
409     fn as_ref(&self) -> &U {
410         <T as AsRef<U>>::as_ref(*self)
411     }
412 }
413
414 // FIXME (#45742): replace the above impls for &/&mut with the following more general one:
415 // // As lifts over Deref
416 // impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
417 //     fn as_ref(&self) -> &U {
418 //         self.deref().as_ref()
419 //     }
420 // }
421
422 // AsMut lifts over &mut
423 #[stable(feature = "rust1", since = "1.0.0")]
424 impl<T: ?Sized, U: ?Sized> AsMut<U> for &mut T where T: AsMut<U>
425 {
426     fn as_mut(&mut self) -> &mut U {
427         (*self).as_mut()
428     }
429 }
430
431 // FIXME (#45742): replace the above impl for &mut with the following more general one:
432 // // AsMut lifts over DerefMut
433 // impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
434 //     fn as_mut(&mut self) -> &mut U {
435 //         self.deref_mut().as_mut()
436 //     }
437 // }
438
439 // From implies Into
440 #[stable(feature = "rust1", since = "1.0.0")]
441 impl<T, U> Into<U> for T where U: From<T>
442 {
443     fn into(self) -> U {
444         U::from(self)
445     }
446 }
447
448 // From (and thus Into) is reflexive
449 #[stable(feature = "rust1", since = "1.0.0")]
450 impl<T> From<T> for T {
451     fn from(t: T) -> T { t }
452 }
453
454
455 // TryFrom implies TryInto
456 #[unstable(feature = "try_from", issue = "33417")]
457 impl<T, U> TryInto<U> for T where U: TryFrom<T>
458 {
459     type Error = U::Error;
460
461     fn try_into(self) -> Result<U, U::Error> {
462         U::try_from(self)
463     }
464 }
465
466 // Infallible conversions are semantically equivalent to fallible conversions
467 // with an uninhabited error type.
468 #[unstable(feature = "try_from", issue = "33417")]
469 impl<T, U> TryFrom<U> for T where U: Into<T> {
470     type Error = !;
471
472     fn try_from(value: U) -> Result<Self, Self::Error> {
473         Ok(U::into(value))
474     }
475 }
476
477 ////////////////////////////////////////////////////////////////////////////////
478 // CONCRETE IMPLS
479 ////////////////////////////////////////////////////////////////////////////////
480
481 #[stable(feature = "rust1", since = "1.0.0")]
482 impl<T> AsRef<[T]> for [T] {
483     fn as_ref(&self) -> &[T] {
484         self
485     }
486 }
487
488 #[stable(feature = "rust1", since = "1.0.0")]
489 impl<T> AsMut<[T]> for [T] {
490     fn as_mut(&mut self) -> &mut [T] {
491         self
492     }
493 }
494
495 #[stable(feature = "rust1", since = "1.0.0")]
496 impl AsRef<str> for str {
497     #[inline]
498     fn as_ref(&self) -> &str {
499         self
500     }
501 }