Traits in RUST
Traits define behavior that a type can implement. They are similar to interfaces in other languages. Here's an example:
rust
trait Printable {
fn print(&self);
}
struct Rectangle {
width: u32,
height: u32,
}
impl Printable for Rectangle {
fn print(&self) {
println!("Rectangle: {} x {}", self.width, self.height);
}
}
fn main() {
let rect = Rectangle { width: 10, height: 20 };
rect.print(); // prints "Rectangle: 10 x 20"
}
No comments:
Post a Comment