Now that I've compiled and installed rust it is time to learn how to write some rust programs. The posts in this series will be from the point of view of a C programmer, as C is my main programming language.

To avoid getting bored programming hello world, fizzbuzz, or Fahrenheit to Celsius converters I decided to learn something in addition to rust. Peter Shirley has released a mini book series on ray tracing. Currently there are three books in the series Ray Tracing in One Weekend, Ray Tracing: the Next Week, and Ray Tracing: The Rest of Your Life. The book series introduces you ray tracing in bite size chunks, making the subject seem less daunting. Combined with Shirley's clear writing makes the series very enjoyable.

The books examples are written in C++, so part of the learning has been to convert C++ programs to rust. The first code snippet that Shirley hands us prints out an 8 bit color image which goes from black on the bottom to full green on top and fully black to red from left to right. Figure 1 shows what the output looks like when piped into a .ppm file and opened in with a file viewer that supports the format, for example eye of gnome or feh.

Graphics Hello World

Figure 1: Hello world! Color graphic.

There are three major ways that my rust code is different to Shirley's C++ code; in printing, for looping, and casting. When printing in rust you call the println!() function, which prints whatever string you send it with a newline on the end. {} are used as place holders for variables, thus printing the pixel values looks like:

      println!("{} {} {}",ir,ig,ib);

For loops in rust are also different. You do not give a variable to loop over but rather define a range. For example the following code will print values from 0 to 9:

for i in 0..10 { 

Now you might be wondering, what if I want to loop in reverse order?. Simple, call .rev() and it will loop from 9 to 0 instead:

for i in (0..10).rev() { 

Type casting an integer in C++ to float could be done like so float(i) where i is an integer. The equivalent in rust is i as float. Therefore dividing two integers and storing the result as a float looks like this in rust:

  let r: f32 = (i as f32)/(j as f32);

r is a 32-bit floating point number and i and j are integers that are type cast to 32-bit floating point nummbers.

Knowing these differences the C++ program can be rewritten to rust and we will get the result shown in figure 1.