rust / intermediate
Snippet
Custom Trait Implementation
Traits define shared behavior. Here Summable is implemented for both [i32] and Vec<i32>. Generic functions like print_stats use trait bounds to accept any type implementing Summable. This achieves polymorphism without inheritance.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
trait Summable {fn sum(&self) -> i32;fn count(&self) -> usize;}impl Summable for [i32] {fn sum(&self) -> i32 {self.iter().fold(0, |acc, &x| acc + x)}fn count(&self) -> usize {self.len()}}impl Summable for Vec<i32> {fn sum(&self) -> i32 {self.as_slice().sum()}fn count(&self) -> usize {self.len()}}fn print_stats<T: Summable>(items: &T) {println!("Count: {}, Sum: {}", items.count(), items.sum());}fn main() {let arr = [1, 2, 3, 4, 5];let vec = vec![10, 20, 30];print_stats(&arr);print_stats(&vec);}
Breakdown
1
trait Summable {
Defines trait with two method signatures
2
impl Summable for [i32] {
Implements trait for slice type directly
3
impl Summable for Vec<i32> {
Implements trait for Vec, delegating to slice implementation
4
fn print_stats<T: Summable>(items: &T)
Generic function constrained by trait bound