π§°
World 10 Β· Super Flexible Code
Generics: Works With Anything
Imagine one labeled box. You can put a phone in it, a notebook, or a set of keys β the box doesnβt care! It just holds whatever you give it. In Rust, that kind of box is called a generic. π§°
A generic lets you write one piece of code that works with many kinds of things, instead of writing it over and over for each kind.
The Big Idea
A generic uses a placeholder name β usually
T β that stands
for "some type, any type." Rust fills in the real type later, when you actually use your code.
A placeholder called T
When you write <T>, youβre telling Rust: βI donβt know the exact type yet β call it
T for now.β T is just a nickname. It could turn into a number, a word, or
anything else when the code runs.
Think of it like thisβ¦
T is like a name tag that says "fill me in later." One box, but it can hold
anything. One piece of code, but it works with any type!
A point that fits any number
Letβs make a Point that has an x and a y. Using <T>, the same Point
can hold whole numbers or numbers with dots (decimals). Press βΆ Run!