17
17
//! Like many traits, these are often used as bounds for generic functions, to
18
18
//! support arguments of multiple types.
19
19
//!
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
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
22
//! - The [`From`] trait is the most flexible, useful for value _and_ reference conversions
23
23
//! - The [`TryFrom`] and [`TryInto`] traits behave like [`From`] and [`Into`], but allow for the
24
24
//! conversion to fail
25
25
//!
26
26
//! As a library author, you should prefer implementing [`From<T>`][`From`] or
27
27
//! [`TryFrom<T>`][`TryFrom`] rather than [`Into<U>`][`Into`] or [`TryInto<U>`][`TryInto`],
28
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.
29
+ //! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a
30
+ //! blanket implementation in the standard library.
31
31
//!
32
- //! # Generic impl
32
+ //! # Generic Implementations
33
33
//!
34
34
//! - [`AsRef`] and [`AsMut`] auto-dereference if the inner type is a reference
35
35
//! - [`From`]`<U> for T` implies [`Into`]`<T> for U`
36
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
37
+ //! - [`From`] and [`Into`] are reflexive, which means that all types can
38
+ //! `into` themselves and `from` themselves
39
39
//!
40
40
//! See each trait for usage examples.
41
41
//!
50
50
51
51
use str:: FromStr ;
52
52
53
- /// A cheap, reference-to-reference conversion.
53
+ /// A cheap reference-to-reference conversion. Used to convert a value to a
54
+ /// reference value within generic code.
54
55
///
55
- /// `AsRef` is very similar to, but different than, [`Borrow`]. See
56
- /// [the book][book] for more.
56
+ /// `AsRef` is very similar to, but serves a slightly different purpose than,
57
+ /// [`Borrow`].
58
+ ///
59
+ /// `AsRef` is to be used when wishing to convert to a reference of another
60
+ /// type.
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.
65
+ ///
66
+ /// The key difference between the two traits is the intention:
67
+ ///
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
71
+ ///
72
+ /// See [the book][book] for a more detailed comparison.
57
73
///
58
74
/// [book]: ../../book/borrow-and-asref.html
59
75
/// [`Borrow`]: ../../std/borrow/trait.Borrow.html
60
76
///
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>`].
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>`].
63
79
///
64
80
/// [`Option<T>`]: ../../std/option/enum.Option.html
65
81
/// [`Result<T, E>`]: ../../std/result/enum.Result.html
66
82
///
83
+ /// # Generic Implementations
84
+ ///
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`)
88
+ ///
67
89
/// # Examples
68
90
///
69
91
/// Both [`String`] and `&str` implement `AsRef<str>`:
@@ -82,11 +104,6 @@ use str::FromStr;
82
104
/// is_hello(s);
83
105
/// ```
84
106
///
85
- /// # Generic Impls
86
- ///
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`)
89
- ///
90
107
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
91
108
pub trait AsRef < T : ?Sized > {
92
109
/// Performs the conversion.
@@ -96,12 +113,21 @@ pub trait AsRef<T: ?Sized> {
96
113
97
114
/// A cheap, mutable reference-to-mutable reference conversion.
98
115
///
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>`].
116
+ /// This trait is similar to `AsRef` but used for converting between mutable
117
+ /// references.
118
+ ///
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>`].
101
121
///
102
122
/// [`Option<T>`]: ../../std/option/enum.Option.html
103
123
/// [`Result<T, E>`]: ../../std/result/enum.Result.html
104
124
///
125
+ /// # Generic Implementations
126
+ ///
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`)
130
+ ///
105
131
/// # Examples
106
132
///
107
133
/// [`Box<T>`] implements `AsMut<T>`:
@@ -118,10 +144,6 @@ pub trait AsRef<T: ?Sized> {
118
144
/// assert_eq!(*boxed_num, 1);
119
145
/// ```
120
146
///
121
- /// # Generic Impls
122
- ///
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`)
125
147
///
126
148
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
127
149
pub trait AsMut < T : ?Sized > {
@@ -130,14 +152,22 @@ pub trait AsMut<T: ?Sized> {
130
152
fn as_mut ( & mut self ) -> & mut T ;
131
153
}
132
154
133
- /// A conversion that consumes `self`, which may or may not be expensive.
155
+ /// A conversion that consumes `self`, which may or may not be expensive. The
156
+ /// reciprocal of [`From`][From].
157
+ ///
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>`].
134
161
///
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>`].
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.
137
166
///
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.
167
+ /// # Generic Implementations
168
+ ///
169
+ /// - [`From<T>`][From]` for U` implies `Into<U> for T`
170
+ /// - [`into`] is reflexive, which means that `Into<T> for T` is implemented
141
171
///
142
172
/// # Examples
143
173
///
@@ -153,11 +183,6 @@ pub trait AsMut<T: ?Sized> {
153
183
/// is_hello(s);
154
184
/// ```
155
185
///
156
- /// # Generic Impls
157
- ///
158
- /// - [`From<T>`][From]` for U` implies `Into<U> for T`
159
- /// - [`into`] is reflexive, which means that `Into<T> for T` is implemented
160
- ///
161
186
/// [`TryInto`]: trait.TryInto.html
162
187
/// [`Option<T>`]: ../../std/option/enum.Option.html
163
188
/// [`Result<T, E>`]: ../../std/result/enum.Result.html
@@ -171,10 +196,31 @@ pub trait Into<T>: Sized {
171
196
fn into ( self ) -> T ;
172
197
}
173
198
174
- /// Construct `Self` via a conversion.
199
+ /// Simple and safe type conversions in to `Self`. It is the reciprocal of
200
+ /// `Into`.
201
+ ///
202
+ /// This trait is useful when performing error handling as described by
203
+ /// [the book][book] and is closely related to the `?` operator.
204
+ ///
205
+ /// When constructing a function that is capable of failing the return type
206
+ /// will generally be of the form `Result<T, E>`.
207
+ ///
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.
211
+ ///
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.
215
+ ///
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>`].
175
219
///
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>`].
220
+ /// # Generic Implementations
221
+ ///
222
+ /// - `From<T> for U` implies [`Into<U>`]` for T`
223
+ /// - [`from`] is reflexive, which means that `From<T> for T` is implemented
178
224
///
179
225
/// # Examples
180
226
///
@@ -186,29 +232,60 @@ pub trait Into<T>: Sized {
186
232
///
187
233
/// assert_eq!(string, other_string);
188
234
/// ```
189
- /// # Generic impls
190
235
///
191
- /// - `From<T> for U` implies [`Into<U>`]` for T`
192
- /// - [`from`] is reflexive, which means that `From<T> for T` is implemented
236
+ /// An example usage for error handling:
237
+ ///
238
+ /// ```
239
+ /// use std::io::{self, Read};
240
+ /// use std::num;
241
+ ///
242
+ /// enum CliError {
243
+ /// IoError(io::Error),
244
+ /// ParseError(num::ParseIntError),
245
+ /// }
246
+ ///
247
+ /// impl From<io::Error> for CliError {
248
+ /// fn from(error: io::Error) -> Self {
249
+ /// CliError::IoError(error)
250
+ /// }
251
+ /// }
252
+ ///
253
+ /// impl From<num::ParseIntError> for CliError {
254
+ /// fn from(error: num::ParseIntError) -> Self {
255
+ /// CliError::ParseError(error)
256
+ /// }
257
+ /// }
258
+ ///
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()?;
264
+ /// Ok(num)
265
+ /// }
266
+ /// ```
193
267
///
194
268
/// [`TryFrom`]: trait.TryFrom.html
195
269
/// [`Option<T>`]: ../../std/option/enum.Option.html
196
270
/// [`Result<T, E>`]: ../../std/result/enum.Result.html
197
271
/// [`String`]: ../../std/string/struct.String.html
198
272
/// [`Into<U>`]: trait.Into.html
199
273
/// [`from`]: trait.From.html#tymethod.from
274
+ /// [book]: ../../book/error-handling.html
200
275
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
201
276
pub trait From < T > : Sized {
202
277
/// Performs the conversion.
203
278
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
204
279
fn from ( T ) -> Self ;
205
280
}
206
281
207
- /// An attempted conversion that consumes `self`, which may or may not be expensive.
282
+ /// An attempted conversion that consumes `self`, which may or may not be
283
+ /// expensive.
208
284
///
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.
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.
212
289
///
213
290
/// [`TryFrom`]: trait.TryFrom.html
214
291
#[ unstable( feature = "try_from" , issue = "33417" ) ]
@@ -236,15 +313,17 @@ pub trait TryFrom<T>: Sized {
236
313
237
314
// As lifts over &
238
315
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
239
- impl < ' a , T : ?Sized , U : ?Sized > AsRef < U > for & ' a T where T : AsRef < U > {
316
+ impl < ' a , T : ?Sized , U : ?Sized > AsRef < U > for & ' a T where T : AsRef < U >
317
+ {
240
318
fn as_ref ( & self ) -> & U {
241
319
<T as AsRef < U > >:: as_ref ( * self )
242
320
}
243
321
}
244
322
245
323
// As lifts over &mut
246
324
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
247
- impl < ' a , T : ?Sized , U : ?Sized > AsRef < U > for & ' a mut T where T : AsRef < U > {
325
+ impl < ' a , T : ?Sized , U : ?Sized > AsRef < U > for & ' a mut T where T : AsRef < U >
326
+ {
248
327
fn as_ref ( & self ) -> & U {
249
328
<T as AsRef < U > >:: as_ref ( * self )
250
329
}
@@ -260,7 +339,8 @@ impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U> {
260
339
261
340
// AsMut lifts over &mut
262
341
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
263
- impl < ' a , T : ?Sized , U : ?Sized > AsMut < U > for & ' a mut T where T : AsMut < U > {
342
+ impl < ' a , T : ?Sized , U : ?Sized > AsMut < U > for & ' a mut T where T : AsMut < U >
343
+ {
264
344
fn as_mut ( & mut self ) -> & mut U {
265
345
( * self ) . as_mut ( )
266
346
}
@@ -276,7 +356,8 @@ impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U> {
276
356
277
357
// From implies Into
278
358
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
279
- impl < T , U > Into < U > for T where U : From < T > {
359
+ impl < T , U > Into < U > for T where U : From < T >
360
+ {
280
361
fn into ( self ) -> U {
281
362
U :: from ( self )
282
363
}
@@ -291,7 +372,8 @@ impl<T> From<T> for T {
291
372
292
373
// TryFrom implies TryInto
293
374
#[ unstable( feature = "try_from" , issue = "33417" ) ]
294
- impl < T , U > TryInto < U > for T where U : TryFrom < T > {
375
+ impl < T , U > TryInto < U > for T where U : TryFrom < T >
376
+ {
295
377
type Error = U :: Error ;
296
378
297
379
fn try_into ( self ) -> Result < U , U :: Error > {
@@ -327,7 +409,8 @@ impl AsRef<str> for str {
327
409
328
410
// FromStr implies TryFrom<&str>
329
411
#[ unstable( feature = "try_from" , issue = "33417" ) ]
330
- impl < ' a , T > TryFrom < & ' a str > for T where T : FromStr {
412
+ impl < ' a , T > TryFrom < & ' a str > for T where T : FromStr
413
+ {
331
414
type Error = <T as FromStr >:: Err ;
332
415
333
416
fn try_from ( s : & ' a str ) -> Result < T , Self :: Error > {
0 commit comments