Skip to content

Commit

Permalink
Rust Traits text
Browse files Browse the repository at this point in the history
  • Loading branch information
Graham authored and Graham committed Sep 21, 2024
1 parent e372a53 commit dbc272f
Showing 1 changed file with 22 additions and 10 deletions.
32 changes: 22 additions & 10 deletions content/post/2024-09-21-RustTraits.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ This concept is interesting and I wanted to write it down as I learned it. I've
the terminology wrong!

Traits can be added to types to allow them to do something, as if these were classes in C++ that already had methods
implemented. So if I want to check if an i32 is divisible by 7, I can add:
implemented.

In this scenario, I'm imagining that it's very importand to check if a number is divisible by seven, and if it actually is
the number seven. I can add a function to the "i32" and "u32" object. I would probably need to do this to i64 too, but
this isn't particularly exciting to reiterate in code below.

```
trait Sevens {
Expand All @@ -31,15 +35,6 @@ impl Sevens for i32 {
7 == *self
}
}
fn main() {
let x: i32 = 9;
let y: u32 = 49;
println!("Is {} divisible by 7? {}", x, x.divisible_by_seven());
println!("Is {} divisible by 7? {}", y, y.divisible_by_seven());
println!("Is {} equal to 7? {}", y, y.is_seven());
println!("Is {} equal to 7? {}", 7, 7.is_seven());
}
```

And if I want the same to work on u32, I can add this to the code:
Expand All @@ -54,3 +49,20 @@ impl Sevens for u32 {
}
}
```

And then main can be added (note, these are all in the same file at the moment as I haven't
imported another file with a "use" declaration.


```
fn main() {
let x: i32 = 9;
let y: u32 = 49;
println!("Is {} divisible by 7? {}", x, x.divisible_by_seven());
println!("Is {} divisible by 7? {}", y, y.divisible_by_seven());
println!("Is {} equal to 7? {}", y, y.is_seven());
println!("Is {} equal to 7? {}", 7, 7.is_seven());
}
```

Ooh, notice I can now do `7.is_seven()`, isn't that interesting.

0 comments on commit dbc272f

Please sign in to comment.