Rust for the Novice Programmer/Strings

Strings edit

A short aside about strings edit

Strings created with the double quotes "" around some text such as the "Hello world!" we created at the start are stored inside the program that is created when we compile it. This means it is easy to find and use when running the program. However, this means we can't change them while the program is running, since all the memory in the program is laid out a certain way. Also strings and characters can be quite complicated. This is because there are so many things to handle; the world isn't just english characters! There are many different languages, many having different alphabets. There are emojis and other special characters. Different formats of storing these different characters will use differing amounts of bytes. If you're working with English, most of the time you will use a standard called UTF-8 which uses 8 bits(one byte) for most common English characters.

In Rust, there are two string types to represent some of this behaviour. There is a primitive type 'str' which is just the starting point and the length of the string. This means that a reference to an str, or &str can be a reference to a string that is stored within the program. The other string type is String, which stores a string like a vector of bytes. Since it is a vector we can modify and change the string. Also since a vector has a start point and a length, we can easily convert a String to a &str, although to convert the other way requires us to clone the data over.

First, let's try to create a function that takes in two Strings and returns one combined String:

 fn combine(string1: String, string2: String) -> String {
     let mut string = string1;
     string.push_str(&string2);
     return string;
 }

What is the push_str() function? Do we have to memorise every function that we want to use? No, this is what documentation is for. Documentation provides us a way to find the structs, functions including types as well as often a written explanation of what they do and how to use them. The documentation for the push_str function is found here: https://doc.rust-lang.org/std/string/struct.String.html#method.push_str . If we read it, we see this:

 pub fn push_str(&mut self, string: &str)
     Appends a given string slice onto the end of this String.

The pub means it is public, so we can use it. The &mut self is shorthand for 'self: &mut String' so it is using self as a mutable reference to a String and it takes in a string of type &str. Since it is a reference, we can use &string2 as an &str since it dereferences to one easily.

Next: Rust for the Novice Programmer/Basic Maths Testing Program