Generic Functions
Medium
+3 pts
🎯 In Python, functions work with any type by default — duck typing:
def middle(items):
if not items:
return None
return items[len(items) // 2]
middle([10, 20, 30]) # 20
middle(["a", "b", "c", "d"]) # "b"
No type annotations needed. If it has __getitem__, it works. If it doesn't — runtime error.
Rust's approach is different: generic functions work with many types, but the compiler verifies at compile time that each type supports the operations you use. The <T> syntax declares a type parameter:
fn middle<T>(items: &[T]) -> Option<&T> {
if items.is_empty() {
None
} else {
Some(&items[items.len() / 2])
}
}
This works with &[i32], &[String], &[bool] — any slice type. The compiler generates …
Login to see the full exercise.