mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-04-23 08:07:38 +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
|
||||
|
||||
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
|
||||
#[derive(Debug)]
|
||||
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 {
|
||||
fn from(from: u32) -> Foo {
|
||||
Foo(format!("Converted from integer: {from}"))
|
||||
@ -41,8 +41,7 @@ fn main() {
|
||||
<details>
|
||||
|
||||
- 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)
|
||||
is simple, and copied here for reference.
|
||||
[definition in the `std` docs][from] is simple, and copied here for reference.
|
||||
|
||||
- Implementations of the trait do not need to cover all possible type
|
||||
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).
|
||||
|
||||
</details>
|
||||
|
||||
[from]: https://doc.rust-lang.org/std/convert/trait.From.html
|
||||
|
Loading…
x
Reference in New Issue
Block a user