rust_implimentation/main.rs
1// ---------------------------------------------------------------------------
2// Part 1 & Part 2: Inheritance-based polymorphism is NOT allowed in Rust.
3// Rust has no concept of struct/class inheritance, so there is no equivalent
4// of Java's `extends`, no base-class vtable dispatch, and no way to declare
5// an abstract base struct with a concrete default method that subclasses
6// inherit. Rust only offers composition and trait-based (interface-based)
7// polymorphism, implemented below as the closest analogues to Parts 3 and 4.
8// ---------------------------------------------------------------------------
9
10/// Part 3: Interface-based polymorphism via trait objects (dynamic dispatch
11/// through a vtable pointer embedded in the fat pointer `&dyn Speaker`).
12trait Speaker {
13 /// Emits the sound associated with this speaker.
14 fn speak(&self);
15}
16
17/// A `Speaker` implementation that barks.
18struct InterfaceDog;
19impl Speaker for InterfaceDog {
20 fn speak(&self) {
21 println!("bark");
22 }
23}
24
25/// A `Speaker` implementation that meows.
26struct InterfaceCat;
27impl Speaker for InterfaceCat {
28 fn speak(&self) {
29 println!("meow");
30 }
31}
32
33/// Dynamic Dispatch via trait object (`dyn Speaker`).
34///
35/// # Arguments
36/// * `s` - A trait object reference resolved at runtime via vtable lookup.
37fn make_speak(s: &dyn Speaker) {
38 s.speak();
39}
40
41/// Part 4: Monomorphic dispatch via a generic function.
42///
43/// The compiler monomorphizes `direct_speak` for each concrete type it is
44/// called with, so the call to `speak` is resolved statically at compile
45/// time (no vtable, no indirection) - analogous to Java calling a method on
46/// a `final` class through a concrete reference.
47trait SingleSpeaker {
48 /// Emits the sound associated with this single, non-polymorphic speaker.
49 fn speak(&self);
50}
51
52/// The sole `SingleSpeaker` implementation; there is nothing else to dispatch to.
53struct PureBreedDog;
54impl SingleSpeaker for PureBreedDog {
55 fn speak(&self) {
56 println!("Woof");
57 }
58}
59
60/// Monomorphic target resolved at compile time via generics.
61///
62/// # Type Parameters
63/// * `T` - Concrete type implementing [`SingleSpeaker`]; a distinct copy of
64/// this function is generated per instantiation, so `speak` is called
65/// directly with no dynamic dispatch.
66///
67/// # Arguments
68/// * `explicit_dog` - Reference to the concrete speaker instance.
69fn direct_speak<T: SingleSpeaker>(explicit_dog: &T) {
70 explicit_dog.speak();
71}
72
73fn main() {
74 let my_dog = InterfaceDog;
75 let my_cat = InterfaceCat;
76
77 make_speak(&my_dog);
78 make_speak(&my_cat);
79
80 let pure_dog = PureBreedDog;
81 direct_speak(&pure_dog);
82}