Codele / Advanced programming
Generics: one code, many types
Write a container once and let it hold any kind of thing, safely. Each box gets a label for the one kind it may hold, and the computer checks that label.
- Generics let you write a container or function once, with a blank type T, and use it for any type.
- Box<int> and Box<string> come from one definition. Each is checked for its own kind of item. Java writes Integer instead of int here.
- The check happens before the program runs in Java, C#, C++ and Go, so a wrong item is a mistake you can fix at your desk, not a crash for a customer.
- Python and JavaScript do not check this before running. Python’s Box[int] is only a hint for tools such as mypy; JavaScript has no type labels at all.
- C++ calls this feature templates, and each Box<T> is built when you use it. Go added generics in version 1.18.
Loading the playable lesson…