mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-04-22 15:57:46 +02:00
Move From
definition into code block (#2678)
This commit is contained in:
parent
c486dd9d80
commit
5704f2061a
@ -5,19 +5,19 @@ Minutes: 5
|
|||||||
# Generic Traits
|
# Generic Traits
|
||||||
|
|
||||||
Traits can also be generic, just like types and functions. A trait's parameters
|
Traits can also be generic, just like types and functions. A trait's parameters
|
||||||
get concrete types when it is used.
|
get concrete types when it is used. For example the [`From<T>`][from] trait is
|
||||||
|
used to define type conversions:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
pub trait From<T>: Sized {
|
||||||
|
fn from(value: T) -> Self;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
```rust,editable
|
```rust,editable
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct Foo(String);
|
struct Foo(String);
|
||||||
|
|
||||||
/* https://doc.rust-lang.org/stable/std/convert/trait.From.html
|
|
||||||
*
|
|
||||||
* pub trait From<T>: Sized {
|
|
||||||
* fn from(value: T) -> Self;
|
|
||||||
* }
|
|
||||||
*/
|
|
||||||
|
|
||||||
impl From<u32> for Foo {
|
impl From<u32> for Foo {
|
||||||
fn from(from: u32) -> Foo {
|
fn from(from: u32) -> Foo {
|
||||||
Foo(format!("Converted from integer: {from}"))
|
Foo(format!("Converted from integer: {from}"))
|
||||||
@ -41,8 +41,7 @@ fn main() {
|
|||||||
<details>
|
<details>
|
||||||
|
|
||||||
- The `From` trait will be covered later in the course, but its
|
- The `From` trait will be covered later in the course, but its
|
||||||
[definition in the `std` docs](https://doc.rust-lang.org/std/convert/trait.From.html)
|
[definition in the `std` docs][from] is simple, and copied here for reference.
|
||||||
is simple, and copied here for reference.
|
|
||||||
|
|
||||||
- Implementations of the trait do not need to cover all possible type
|
- Implementations of the trait do not need to cover all possible type
|
||||||
parameters. Here, `Foo::from("hello")` would not compile because there is no
|
parameters. Here, `Foo::from("hello")` would not compile because there is no
|
||||||
@ -58,3 +57,5 @@ fn main() {
|
|||||||
[specialization](https://rust-lang.github.io/rfcs/1210-impl-specialization.html).
|
[specialization](https://rust-lang.github.io/rfcs/1210-impl-specialization.html).
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
|
[from]: https://doc.rust-lang.org/std/convert/trait.From.html
|
||||||
|
Loading…
x
Reference in New Issue
Block a user