@@ -5,19 +5,19 @@ Minutes: 5
5
5
# Generic Traits
6
6
7
7
Traits can also be generic, just like types and functions. A trait's parameters
8
- get concrete types when it is used.
8
+ get concrete types when it is used. For example the [ ` From<T> ` ] [ from ] trait is
9
+ used to define type conversions:
10
+
11
+ ``` rust
12
+ pub trait From <T >: Sized {
13
+ fn from (value : T ) -> Self ;
14
+ }
15
+ ```
9
16
10
17
``` rust,editable
11
18
#[derive(Debug)]
12
19
struct Foo(String);
13
20
14
- /* https://doc.rust-lang.org/stable/std/convert/trait.From.html
15
- *
16
- * pub trait From<T>: Sized {
17
- * fn from(value: T) -> Self;
18
- * }
19
- */
20
-
21
21
impl From<u32> for Foo {
22
22
fn from(from: u32) -> Foo {
23
23
Foo(format!("Converted from integer: {from}"))
@@ -41,8 +41,7 @@ fn main() {
41
41
<details >
42
42
43
43
- The ` From ` trait will be covered later in the course, but its
44
- [ definition in the ` std ` docs] ( https://doc.rust-lang.org/std/convert/trait.From.html )
45
- is simple, and copied here for reference.
44
+ [ definition in the ` std ` docs] [ from ] is simple, and copied here for reference.
46
45
47
46
- Implementations of the trait do not need to cover all possible type
48
47
parameters. Here, ` Foo::from("hello") ` would not compile because there is no
@@ -58,3 +57,5 @@ fn main() {
58
57
[ specialization] ( https://rust-lang.github.io/rfcs/1210-impl-specialization.html ) .
59
58
60
59
</details >
60
+
61
+ [ from ] : https://doc.rust-lang.org/std/convert/trait.From.html
0 commit comments