πŸ”Ž
World 12 Β· A Real Project

Build a Search Tool

Have you ever pressed Ctrl+F to search for a word on a page? Every spot that has your word lights up. πŸ”¦ Today you’re going to build your own search tool in Rust β€” a real program that hunts through some text and shows you exactly which lines contain the word you’re looking for.

This is a great moment to bring everything together: functions, vectors, strings, slices, and loops. One small program, all your skills working as a team.

The Big Idea A search tool looks at text line by line and keeps only the lines that contain a special word, called the query. We collect those matching lines into a vector and print them out.

Looking through every line

Text is made of lines, like sentences stacked on top of each other. Rust gives us a handy helper called .lines() that walks through them one at a time. And .contains() checks if a line has our word inside it. Let’s peek at the idea:

See how only the lines with red showed up? The green pear line got skipped because it doesn’t contain our word. That’s a search tool in a nutshell. πŸ₯œ

New word The query is the word you are searching for β€” the thing you type into the search box.

Putting it in a function

A real tool needs a tidy, well-defined job. Let’s write a function called search that takes a query and the contents, and hands back a vector of matching lines. Each line we return is a slice β€” a borrowed view into part of the text, so we don’t have to copy anything. πŸͺŸ

We kept the text right inside the program so it’s easy to run anywhere β€” no files needed. πŸ“¦ Our search function starts with an empty vector, checks every line, and pushes the ones that match. Then main prints each result.

Ferris says: That little 'a is a lifetime. It's just Rust's way of promising the lines we hand back will live as long as the text they came from. Don't sweat the details β€” you'll meet lifetimes again later! πŸ¦€
Try this! Change query to "the" and press β–Ά Run. How many lines match now? Then try "Crabs" and watch the results change.

Quick quiz

What does .contains(query) do for each line?

Yes! .contains() answers a true-or-false question: is the query word inside this line? If yes, we keep the line. 🎯

You learned… You built a real search tool! You used .lines() to walk through text, .contains() to find matches, and a vector to collect the lines your search function returns. You just tied together functions, vectors, strings, slices, and loops into one working program. πŸŽ‰ Next up, World 13: Fancy Function Tricks β€” where functions pick up some powerful new moves. πŸͺ„