Skip to content

Commit

Permalink
rust post
Browse files Browse the repository at this point in the history
  • Loading branch information
Graham authored and Graham committed Sep 21, 2024
1 parent 8a42cc7 commit ce99d3b
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions content/post/2024-09-21-RustTraits.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
---
title: Rust Traits
subtitle: Learning Rust
date: 2024-09-21
tags: [
"programming",
"code",
"rust",
]
---

# Rust Traits, what are they?

This concept is interesting and I wanted to write it down as I learned it. I've just started learing Rust and will have
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:

```
trait Sevens{
fn is_seven(&self) -> bool;
fn divisible_by_seven(&self) -> bool;
}
impl Sevens for i32 {
fn divisible_by_seven(&self) -> bool{
self%7 == 0
}
fn is_seven(&self) -> bool{
7 == *self
}
}
impl Sevens for u32 {
fn divisible_by_seven(&self) -> bool{
self%7 == 0
}
fn is_seven(&self) -> bool{
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());
}
```

0 comments on commit ce99d3b

Please sign in to comment.