Struct and Traits in Rust

Rust is not an OOP language. However, is possible to have similar behavior using Structs and traits. Traits are great because allow us to create common and interfaces and allow structure for generic coding. The struct is like a struct in C. They allow us to have Pojos and hold both data and behavior using traits.  Today I want to show you guys how we can work with struct and traits in Rust. This is another short video focusing on understanding and also you will learn somethings about macros as well.  So I hope you guys liked it, let's get started !!!



Video


struct and traits in Rust from Diego Pacheco on Vimeo.


Code

use std::fmt;
trait Animal {
fn greet(&self) -> String;
}
#[derive(Debug)]
struct Cat{
name: String,
}
#[derive(Debug)]
struct Dog{
name: String,
}
impl Animal for Dog {
fn greet(&self) -> String {
return String::from("rof rof rof");
}
}
impl Animal for Cat {
fn greet(&self) -> String {
return String::from("meow meow meow... ");
}
}
macro_rules! impl_T {
(for $($t:ty),+) => {
$(impl fmt::Display for $t {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.greet())
}
})*
}
}
impl_T!(for Cat,Dog);
fn main() {
let dog = Dog{
name: String::from("Max"),
};
println!("{:?}",dog);
let cat = Cat{
name: String::from("Gandalf"),
};
println!("{:?}",cat);
println!("Dogs {} and Cats {} greeting you!", dog, cat);
}
view raw main.rs hosted with ❤ by GitHub


Cheers,
Diego Pacheco

Popular posts from this blog

Having fun with Zig Language

C Unit Testing with Check

Cool Retro Terminal