Throw it in Reverse

My old-guy approach to my first Rust Exercism exercise – and some Rust basics

Parked car upside down on roof
What!? I’m in my spot! Now lemme find some change for the meter!

Exercism starts me with one of many easy problems they have in their Rust track to solve: write a function that, provided a string, will return that string reversed. So, just flip it!

My ancient C upbringing shines at this point – my first inclination is to loop through the characters in the provided string, in reverse order, and append each char to a new string. So, how to do that in Rust? I end up with this:

pub fn reverse(input: &str) -> String {
     let mut rev_str = String::new();
     for byte in input.chars().rev() {
         rev_str.push(byte);
     }
     rev_str
}

Here, reverse is defined as a (public) function that will accept a string as a parameter (named input) and return a string to the caller. It creates a new string variable rev_str to hold the reversed string while we build it, and then iterates over a loop of the input string’s characters, in reverse order, and pushes each one onto our rev_str variable, and returns it at the end.




Strongly Typed – Really Slam Those Keys

Firstly, Rust is a statically and strongly typed language; if the compiler can’t figure out what type to make a variable, it requires you to specify the type. We also need to remember that all Rust variables are, by default, immutable – once their value is set (at instantiation) it cannot be changed. Anyway, we identify the variable type for our parameter coming in, our holding variable within the function, and our return value. But all three look different, you say?

The easiest is the return value, simply a String; a fancier version of the primitive str type. Our holding variable is the same type – it has to be, it is the variable we end up returning – String::new() just means we are asking for a new, empty String type to stuff our characters in (ALL variables in Rust must be initialized with a default value – this one starts “empty”). The mut you see here is telling the compiler we want a mutable variable – since we will be changing the value as we loop. The incoming parameter however, introduces us to Rust’s use of Ownership, Borrowing, and Lifetimes. Basically, our input param is “borrowing” the variable coming in (passed as a reference) and the borrow will go away once our variable goes out of scope.

Roller coaster with loop in the distance, on hill

Notice we didn’t specify a type for our looping variable byte. Rust forgives us – it can easily identify that byte needs to be a char type because that is what input.chars() will be returning (calling rev() just reverses the order).

Finally (pun intended), if Rust sees an expression with no trailing ; it uses that as the return value and ends the function. You can still specify return – for instance, if you are in the middle of a function and need to exit early.

What I will find out though, when I submit this as my answer to the Exercism problem, is that I’m Rusting wrong (and showing my age)!

Exercise with Exercism

Making Rust a destination education

Exercise equipment

I enjoy being outside, hiking trails, exploring the wilderness – I live just a few miles from where the Appalachian Trail crosses the road and heads up a mountain to one of the most photographed spots on the entire 2200 mile trek: McAfee Knob. In fact, that perfectly explains my idiosyncrasy with hiking: I’m an amateur photographer and I need a photogenic destination. If the trail just loops a mile or two in the woods, I’m not so anxious to get started. It doesn’t take much for a landscape photographer though: a waterfall, a foggy glen, a 270-degree panoramic view! But, what about a Rust destination? Rust programming exercises?

Panoramic view from Virginia mountain
A slice of the panoramic view from McAfee Knob in Virginia

Rust Objective

When sitting down to learn Rust – I need an objective as well. I need somewhere to go so I don’t feel like I’m wandering in the woods with no destination. I need some programming problems to work on; something to rewrite and refine as I learn different aspects and strengths of a language.

I found Exercism. This site currently supports dozens of programming languages and each has exercises for you to program a solution. The interface is wonderful though, because you install a management application on your development box and write, test, and run your solutions in your home, native environment. Exercism also includes many helpful external learning links about each language.

When the built-in tests for the current problem are passing and you think your solution is complete, you submit your answer back to their server with the installed app and a tutor will give you feedback on your solution. Everything might be great, in which case there might be bonus problems to solve or it may unlock additional exercises for you to try, if you choose the “instructional” track. You can also choose the “independent” mode and simply solve problems in any order you like – perhaps skipping all the “easy” exercises if this is a language you are already familiar with.




Programming Exercises

Maybe I’ll eventually settle on a bigger, more boring app to work on, like the dreaded address book or book collection application (ugh, or maybe not!) Until I do, I’m enjoying going through these exercises and others like it – the book Cracking the Coding Interview: 189 Programming Questions and Solutions by Gayle Laakmann McDowell would be another source of practice exercises to work through, so I’ll probably pull from sources like that as well.

However, I’m just at the start of the trail…

Start of fire-trail headed towards McAfee Knob
The start of the McAfee Knob trail, if you are beginning at the parking lot and not from Springer Mountain in Georgia or Mount Katahdin in Maine.

My First Rust Program

println!(“Hello, World!”);

Rusty metal texture

My first post on Rust programming (well, you could go back and read my welcome post), but my first Rust program anyway… oh what will it be!? Well, I’m boring and predictable, so a Hello World app sounds perfect!

What to expect

This is not going to be a hold-your-hand Rust learning experience. I’m planning that you will read along in the Rust books (both the online, supplied one and maybe an O’Reilly book I am reading it on their Online Learning site) and get Rust installed yourself and start programming. I’m just documenting my travels through the Rust world as I try to teach an old dog (me) some new tricks.

June 17,2019 and I’m starting off with Rust version 1.35.0, and with no further delay, my first Rust program!

fn main() {
  println!("Hello, World!");
}

The book I’m following is keeping it a secret why I am using the println! macro instead of the actual println call, but that’s ok, I can live with secrets.

Starting steps

BTW, I used the Rust-supplied management program cargo to get this started:

cargo init hello_cargo
cd hello_cargo
<edit src/main.rs>
cargo test
cargo run

Of course, passing zero tests is easy!

Ok, I haven’t written in C in 30 years (or in Pascal for a few more than that), but this feels vaguely familiar and there’s not really much to learn here, as usual with a Hello, World script. The curly braces and semi-colons feel right at home in my perl brain.

Note: after a link indicates the link is an Amazon affiliate link