interface.md (1277B)
1 # Interface 2 3 In Rust, the concept of "programming to an interface/supertype" is achieved 4 using traits — Rust's equivalent of interfaces or abstract supertypes. 5 6 1. Define the "Supertype" (Trait) 7 8 ```rust 9 trait Animal { 10 fn make_sound(&self); 11 } 12 ``` 13 14 2. Concrete Implementations 15 16 ```rust 17 struct Dog; 18 struct Cat; 19 20 impl Animal for Dog { 21 fn make_sound(&self) { 22 println!("Woof!"); 23 } 24 } 25 26 impl Animal for Cat { 27 fn make_sound(&self) { 28 println!("Meow!"); 29 } 30 } 31 ``` 32 33 ## Static Dispatch (resolved at compile time — faster) 34 35 ```rust 36 fn interact(animal: &impl Animal) { 37 animal.make_sound(); 38 } 39 40 let animal = Dog; 41 interact(&animal); // Works for any Animal implementor 42 ``` 43 44 ## Dynamic dispatch (resolved at runtime — more flexible) 45 46 ```rust 47 fn interact(animal: &dyn Animal) { 48 animal.make_sound(); 49 } 50 51 let animal: &dyn Animal = &Dog; // Variable typed as the trait, not Dog 52 animal.make_sound(); 53 ``` 54 55 ## Assigning at Runtime 56 57 ```rust 58 fn get_animal(sound_type: &str) -> Box<dyn Animal> { 59 match sound_type { 60 "dog" => Box::new(Dog), 61 _ => Box::new(Cat), 62 } 63 } 64 65 fn main() { 66 let animal = get_animal("dog"); // We don't know the concrete type here 67 animal.make_sound(); // All we care about is make_sound() 68 } 69 ```