🧰
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!

</div> We wrote `Point` **once**, but used it two different ways. The first time `T` became a whole number, and the second time `T` became a decimal. Same box, different contents! 🎁
Ferris says: Generics save you from copy-pasting the same code again and again. Write it once, use it everywhere. Less typing, fewer mistakes! πŸ¦€
Try this! Add a third point with the values x: 0 and y: 0, then print it too. Press β–Ά Run to see all three!
## Quick quiz

What does the T in Point<T> mean?

Yes! T is a stand-in for "any type." Rust fills in the real type when you use it. πŸŽ‰

You learned… Generics let one function or struct work with many types using a placeholder like <T> β€” like a labeled box that fits anything. Next up: Traits: Shared Superpowers, where different types learn to share the same ability! ⭐