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
29
29
//! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a blanket implementation
30
30
//! 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`
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 reference value
54
+ /// 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, [`Borrow`].
57
+ ///
58
+ /// `AsRef` is to be used when wishing to convert to a reference of another type.
59
+ /// `Borrow` is more related to the notion of taking the reference. It is useful when wishing to abstract
60
+ /// over the type of reference (`&T`, `&mut T`) or allow both the referenced and owned type to be treated in the same manner.
61
+ /// The key difference between the two traits is the intention:
62
+ ///
63
+ /// - Use `AsRef` when goal is to simply convert into a reference
64
+ /// - Use `Borrow` when goal is related to writing code that is agnostic to the type of borrow and if is reference or value
65
+ ///
66
+ /// See [the book][book] for a more detailed comparison.
57
67
///
58
68
/// [book]: ../../book/borrow-and-asref.html
59
69
/// [`Borrow`]: ../../std/borrow/trait.Borrow.html
@@ -64,7 +74,23 @@ use str::FromStr;
64
74
/// [`Option<T>`]: ../../std/option/enum.Option.html
65
75
/// [`Result<T, E>`]: ../../std/result/enum.Result.html
66
76
///
77
+ /// # Generic Implementations
78
+ ///
79
+ /// - `AsRef` auto-dereferences if the inner type is a reference or a mutable
80
+ /// reference (e.g.: `foo.as_ref()` will work the same if `foo` has type `&mut Foo` or `&&mut Foo`)
81
+ ///
67
82
/// # Examples
83
+ /// An example implementation of the trait is [`Path`].
84
+ ///
85
+ /// [`Path`]: ../../std/struct.Path.html
86
+ ///
87
+ /// ```
88
+ /// impl AsRef<Path> for str {
89
+ /// fn as_ref(&self) -> &Path {
90
+ /// Path::new(self)
91
+ /// }
92
+ /// }
93
+ /// ```
68
94
///
69
95
/// Both [`String`] and `&str` implement `AsRef<str>`:
70
96
///
@@ -82,11 +108,6 @@ use str::FromStr;
82
108
/// is_hello(s);
83
109
/// ```
84
110
///
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
111
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
91
112
pub trait AsRef < T : ?Sized > {
92
113
/// Performs the conversion.
@@ -96,12 +117,19 @@ pub trait AsRef<T: ?Sized> {
96
117
97
118
/// A cheap, mutable reference-to-mutable reference conversion.
98
119
///
120
+ /// This trait is similar to `AsRef` but used for converting mutable references.
121
+ ///
99
122
/// **Note: this trait must not fail**. If the conversion can fail, use a dedicated method which
100
123
/// returns an [`Option<T>`] or a [`Result<T, E>`].
101
124
///
102
125
/// [`Option<T>`]: ../../std/option/enum.Option.html
103
126
/// [`Result<T, E>`]: ../../std/result/enum.Result.html
104
127
///
128
+ /// # Generic Implementations
129
+ ///
130
+ /// - `AsMut` auto-dereferences if the inner type is a reference or a mutable
131
+ /// reference (e.g.: `foo.as_ref()` will work the same if `foo` has type `&mut Foo` or `&&mut Foo`)
132
+ ///
105
133
/// # Examples
106
134
///
107
135
/// [`Box<T>`] implements `AsMut<T>`:
@@ -118,10 +146,13 @@ pub trait AsRef<T: ?Sized> {
118
146
/// assert_eq!(*boxed_num, 1);
119
147
/// ```
120
148
///
121
- /// # Generic Impls
149
+ /// Implementing `AsMut`:
122
150
///
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`)
151
+ /// ```
152
+ /// impl Type {
153
+ /// let a = 1;
154
+ /// }
155
+ /// ```
125
156
///
126
157
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
127
158
pub trait AsMut < T : ?Sized > {
@@ -130,7 +161,7 @@ pub trait AsMut<T: ?Sized> {
130
161
fn as_mut ( & mut self ) -> & mut T ;
131
162
}
132
163
133
- /// A conversion that consumes `self`, which may or may not be expensive.
164
+ /// A conversion that consumes `self`, which may or may not be expensive. The reciprocal of [`From`][From].
134
165
///
135
166
/// **Note: this trait must not fail**. If the conversion can fail, use [`TryInto`] or a dedicated
136
167
/// method which returns an [`Option<T>`] or a [`Result<T, E>`].
@@ -139,6 +170,11 @@ pub trait AsMut<T: ?Sized> {
139
170
/// the [`From`][From] trait, which offers greater flexibility and provides an equivalent `Into`
140
171
/// implementation for free, thanks to a blanket implementation in the standard library.
141
172
///
173
+ /// # Generic Implementations
174
+ ///
175
+ /// - [`From<T>`][From]` for U` implies `Into<U> for T`
176
+ /// - [`into`] is reflexive, which means that `Into<T> for T` is implemented
177
+ ///
142
178
/// # Examples
143
179
///
144
180
/// [`String`] implements `Into<Vec<u8>>`:
@@ -153,11 +189,6 @@ pub trait AsMut<T: ?Sized> {
153
189
/// is_hello(s);
154
190
/// ```
155
191
///
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
192
/// [`TryInto`]: trait.TryInto.html
162
193
/// [`Option<T>`]: ../../std/option/enum.Option.html
163
194
/// [`Result<T, E>`]: ../../std/result/enum.Result.html
@@ -171,11 +202,24 @@ pub trait Into<T>: Sized {
171
202
fn into ( self ) -> T ;
172
203
}
173
204
174
- /// Construct `Self` via a conversion.
205
+ /// Simple and safe type conversions in to `Self`. It is the reciprocal of `Into`.
206
+ ///
207
+ /// This trait is useful when performing error handling as described by [the book][book] and is closely related to the `?` operator.
208
+ ///
209
+ /// When constructing a function that is capable of failing the return type will generally be of the form `Result<T, E>`.
210
+ /// The `From` trait allows for simplification of error handling by providing a means of returning a single error type that encapsulates
211
+ /// numerous possible erroneous situations.
212
+ /// This trait is not limited to error handling, rather the general case for this trait would be in any type conversions to have an
213
+ /// explicit definition of how they are performed.
175
214
///
176
215
/// **Note: this trait must not fail**. If the conversion can fail, use [`TryFrom`] or a dedicated
177
216
/// method which returns an [`Option<T>`] or a [`Result<T, E>`].
178
217
///
218
+ /// # Generic Implementations
219
+ ///
220
+ /// - `From<T> for U` implies [`Into<U>`]` for T`
221
+ /// - [`from`] is reflexive, which means that `From<T> for T` is implemented
222
+ ///
179
223
/// # Examples
180
224
///
181
225
/// [`String`] implements `From<&str>`:
@@ -186,17 +230,42 @@ pub trait Into<T>: Sized {
186
230
///
187
231
/// assert_eq!(string, other_string);
188
232
/// ```
189
- /// # Generic impls
190
233
///
191
- /// - `From<T> for U` implies [`Into<U>`]` for T`
192
- /// - [`from`] is reflexive, which means that `From<T> for T` is implemented
234
+ /// An example usage for error handling:
235
+ ///
236
+ /// ```
237
+ /// enum CliError {
238
+ /// IoError(io::Error),
239
+ /// ParseError(num::ParseIntError),
240
+ /// }
241
+ ///
242
+ /// impl From<io::Error> for MyError {
243
+ /// fn from(error: io::Error) -> Self {
244
+ /// CliError::IoError(error)
245
+ /// }
246
+ /// }
247
+ ///
248
+ /// impl From<num::ParseIntError> for MyError {
249
+ /// fn from(error: io::Error) -> Self {
250
+ /// CliError::ParseError(error)
251
+ /// }
252
+ /// }
253
+ ///
254
+ /// fn open_and_parse_file(file_name: &str) -> Result<i32, MyError> {
255
+ /// let file = std::fs::File::open("test")?;
256
+ /// let mut contents = String::new();
257
+ /// file.read_to_string(&mut contents)?;
258
+ /// let num: i32 = contents.trim().parse()?;
259
+ /// }
260
+ /// ```
193
261
///
194
262
/// [`TryFrom`]: trait.TryFrom.html
195
263
/// [`Option<T>`]: ../../std/option/enum.Option.html
196
264
/// [`Result<T, E>`]: ../../std/result/enum.Result.html
197
265
/// [`String`]: ../../std/string/struct.String.html
198
266
/// [`Into<U>`]: trait.Into.html
199
267
/// [`from`]: trait.From.html#tymethod.from
268
+ /// [book]: ../../book/error-handling.html#the-from-trait
200
269
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
201
270
pub trait From < T > : Sized {
202
271
/// Performs the conversion.
@@ -236,15 +305,19 @@ pub trait TryFrom<T>: Sized {
236
305
237
306
// As lifts over &
238
307
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
239
- impl < ' a , T : ?Sized , U : ?Sized > AsRef < U > for & ' a T where T : AsRef < U > {
308
+ impl < ' a , T : ?Sized , U : ?Sized > AsRef < U > for & ' a T
309
+ where T : AsRef < U >
310
+ {
240
311
fn as_ref ( & self ) -> & U {
241
312
<T as AsRef < U > >:: as_ref ( * self )
242
313
}
243
314
}
244
315
245
316
// As lifts over &mut
246
317
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
247
- impl < ' a , T : ?Sized , U : ?Sized > AsRef < U > for & ' a mut T where T : AsRef < U > {
318
+ impl < ' a , T : ?Sized , U : ?Sized > AsRef < U > for & ' a mut T
319
+ where T : AsRef < U >
320
+ {
248
321
fn as_ref ( & self ) -> & U {
249
322
<T as AsRef < U > >:: as_ref ( * self )
250
323
}
@@ -260,7 +333,9 @@ impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U> {
260
333
261
334
// AsMut lifts over &mut
262
335
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
263
- impl < ' a , T : ?Sized , U : ?Sized > AsMut < U > for & ' a mut T where T : AsMut < U > {
336
+ impl < ' a , T : ?Sized , U : ?Sized > AsMut < U > for & ' a mut T
337
+ where T : AsMut < U >
338
+ {
264
339
fn as_mut ( & mut self ) -> & mut U {
265
340
( * self ) . as_mut ( )
266
341
}
@@ -276,7 +351,9 @@ impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U> {
276
351
277
352
// From implies Into
278
353
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
279
- impl < T , U > Into < U > for T where U : From < T > {
354
+ impl < T , U > Into < U > for T
355
+ where U : From < T >
356
+ {
280
357
fn into ( self ) -> U {
281
358
U :: from ( self )
282
359
}
@@ -285,13 +362,17 @@ impl<T, U> Into<U> for T where U: From<T> {
285
362
// From (and thus Into) is reflexive
286
363
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
287
364
impl < T > From < T > for T {
288
- fn from ( t : T ) -> T { t }
365
+ fn from ( t : T ) -> T {
366
+ t
367
+ }
289
368
}
290
369
291
370
292
371
// TryFrom implies TryInto
293
372
#[ unstable( feature = "try_from" , issue = "33417" ) ]
294
- impl < T , U > TryInto < U > for T where U : TryFrom < T > {
373
+ impl < T , U > TryInto < U > for T
374
+ where U : TryFrom < T >
375
+ {
295
376
type Error = U :: Error ;
296
377
297
378
fn try_into ( self ) -> Result < U , U :: Error > {
@@ -327,7 +408,9 @@ impl AsRef<str> for str {
327
408
328
409
// FromStr implies TryFrom<&str>
329
410
#[ unstable( feature = "try_from" , issue = "33417" ) ]
330
- impl < ' a , T > TryFrom < & ' a str > for T where T : FromStr {
411
+ impl < ' a , T > TryFrom < & ' a str > for T
412
+ 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