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.
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. π₯
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.
'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! π¦
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. π―
.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. πͺ