Brandon Eleuterio

Articles

Learning Rust – Part 2: Refactoring Into a Struct

Brandon Eleuterio

In Part 1 of this Learning Rust series, I wrote code to create a rainbow square. Now it’s time to refactor and hope the rainbow square is still there.

RGB Image

What and Why

Refactoring is a sort of reorganizing we coders do periodically to make our work easier to read and use. It’s like keeping your desk organized so you can find stuff later. In this case, I moved some code from the main.rs file to a new lib.rs file. Then I created a new struct called Vec3 which will make it easier to create colors and vectors as this project moves along. The main role of Vec3 is to store three numbers. For now, these numbers will represent colors as different combinations of red, green, and blue.

#[derive(Clone, Copy)]
pub struct Vec3 {
    e: [f64; 3],
}

Challenges

Initially, I used a struct called vec from Rust’s standard library to do the work of storing numbers, however, I quickly ran into issues. I think I chose vec because the name matched my struct’s name. A simple array I named ‘e’ turned out to be a much better choice.

I left out one utility function that overloads the output stream operator in C++ because I don’t think it’s necessary in Rust. We’ll see if I’m right.

Vec3 has a lot of operator overloads. Coding these in Rust takes a bit more code than in C++. Here’s the one for the multiplication operator:

impl ops::Mul<&Vec3> for f64 {
    type Output = Vec3;
    fn mul(self, other: &Vec3) -> Self::Output {
        other * self
    }
}

Kind of verbose.

Not Much to See Here

Nothing new visual to show for this post, other than making sure the same rainbow square is generated. My code is here and the book I’m using is here if you’d like to follow along. If we’re lucky, the next chapter will give us a different color square! Baby steps.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top