I am not one of those smart programmers. Rust is overwhelming! But, then the mysterious force isn’t allowing me to give up. So I started reading Rust in Action. Later, I thougt why not take notes and share it with fellow explorers.
I am writing a program to search a given string in a pile of text. I want the out put to show me the exact line with the string and the one above and below. Just to get the context.
Starting a new project was pretty simple
Here’s the plan
- Go through all the lines and see if the line has a string.
- If the line has the string then tag that line by storing it in an array.
- Later, loop through the text again see if it’s above or below the marked line.
- Print those lines to provide context.
I read variables are by default immutable (can’t be changed) in Rust. But I don’t understand, why it’s still called variables?
Now, I need an array that can store line numbers of the text with the query string.
“mut” is to tell Rust that it’s a real variable and we should be allow change it.
This array needs to be of dynamic length or in other words a vector.
Now, what would be the type of elements inside the vector. In this case line numbers (ex: 1, 4, 1000). So basically positive integers or technically unsigned integer.
Finally we need to initalise it, you are familar with “new …()” in other languages.
“vec!” is shorthand for “Vec::new()”.
Yea, too many stuff. Because unlike other languages Rust don’t want to make assumptions. Giving it clarity on things, helps Rust detect issues early and optimize it for performance.
Finally we need a vector to store the context lines.
For each match, we will need a vector with three elements (the line above, the line below and the line itself) along with line numbers. Basically, we are creating a vector inside a vector.
Here’s a visualization of the above line to help you understand. “usize” is for the line no, “String” is to store the line.
Alright, let’s iterate through the lines as tag the once that contains the query string.
If there’s no match we want to stop the program
Now let’s perform another iteration to store the context.
Apparently CPUs have some issues with negative values, so we are ensuring resulting number don’t go below 0.
We cannot use “line” directly because it’s a reference, we need to the above line to copy the value and make it storable as a string.
One last loop to print the context.
Yea I too found it wierd, but I will solve the puzzle in an upcoming post and explain.
Let’s test it out.
Here’s the output.
You can find the full source code here.
I am creating a small community for curios and audicious people who want to learn difficult technologies like Rust. Join us here, so that you won’t miss out on the upcoming posts.