Skip to content

Instantly share code, notes, and snippets.

@AlphaSheep
Last active September 29, 2023 12:35
Show Gist options
  • Save AlphaSheep/77fccd1291ecaef0ea8e12c44b0a33bb to your computer and use it in GitHub Desktop.
Save AlphaSheep/77fccd1291ecaef0ea8e12c44b0a33bb to your computer and use it in GitHub Desktop.
Rust Examples
fn main() {
let original_owner = String::from("Something");
let new_owner = original_owner;
println!("{}", original_owner);
}
// A public function that takes two integers and returns double their sum
pub fn add_and_double(x: i32, y: i32) -> i32 {
2 * _add(x, y)
}
// A private helper function that adds two integers
fn _add(x: i32, y: i32) -> i32 {
x + y
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add_and_double() {
assert_eq!(add_and_double(2, 3), 10);
assert_eq!(add_and_double(0, 0), 0);
}
#[test]
fn test_add() {
assert_eq!(_add(2, 3), 5);
assert_eq!(_add(0, 0), 0);
}
}
fn cross_the_pond(animal: impl Swim) {
animal.swim();
}
struct Duck {
name: String,
}
impl Swim for Duck {
fn swim(&self) {
println!("{} paddles furiously...", self.name);
}
}
struct Elephant {
name: String,
}
impl Swim for Elephant {
fn swim(&self) {
println!("{} is actually just walking on the bottom...", self.name);
}
}
fn main() {
let duck = Duck { name: String::from("Sir Quacks-a-lot") };
let ellie = Elephant { name: String::from("Ellie BigEndian") };
println!("Crossing the pond...");
cross_the_pond(duck);
cross_the_pond(ellie);
}
trait Swim {
fn swim(&self);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment