-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- 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.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | ||
} | ||
``` |