Generic Structs
Medium
+3 pts
🎯 Python's classes can hold any type without declaring it:
class Container:
def __init__(self, item):
self.item = item
Container(42)
Container("hello")
Container([1, 2, 3])
No type declarations needed — item can be anything. With type hints, you can be more specific:
from typing import Generic, TypeVar
T = TypeVar("T")
class Container(Generic[T]):
def __init__(self, item: T):
self.item = item
But Python's generics are only for type checkers. At runtime, Container[int] and Container[str] are the same class.
Rust's generic structs are different — they're real, distinct types at compile time:
struct Container<T> {
item: T,
}
// Container<i32> and Container<String> are different types
// The compiler generates optimized code for each
Defining generic structs
The <T> after the struct name declares a type parameter. Use it in fields:
struct Container<T> {
item: T,
}
struct Entry<K, V> {
key: K,
val: V,
}
…
Login to see the full exercise.
Topics