Created
April 27, 2025 08:22
-
-
Save jwbensley/ac233e1e543011e2d91227774e0bff9a to your computer and use it in GitHub Desktop.
Parent / child traits in rust
This file contains hidden or 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
trait Parent { | |
fn print_x(&self) { | |
println!("X is: {}", self.get_x()); | |
} | |
fn get_x(&self) -> u16; | |
} | |
trait Child: Parent { | |
fn child_fn(&self) { | |
println!("child_fn..."); | |
self.print_x(); | |
} | |
} | |
struct A { | |
x: u16 | |
} | |
struct B { | |
x: u16 | |
} | |
impl A { | |
fn a_only(&self) { | |
println!("This is A"); | |
} | |
} | |
impl Parent for A { | |
fn get_x(&self) -> u16 { | |
self.x | |
} | |
} | |
impl Child for A {} | |
impl Parent for B { | |
fn get_x(&self) -> u16 { | |
self.x | |
} | |
} | |
impl Child for B {} | |
fn main() { | |
let a = A{ x: 5 }; | |
a.a_only(); // Method implemented for this object only | |
a.child_fn(); // Method implemented on shared trait | |
let b = B { x: 10 }; | |
b.child_fn(); // Method implemented on shared trait | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment