From the course: Rust Essential Training

Char data types - Rust Tutorial

From the course: Rust Essential Training

Start my 1-month free trial

Char data types

- [Narrator] The Char data type can be used to represent a single character such as a single letter or perhaps a number. In Rust, the Char data type is a Unicode scalar value and all Char's take up exactly four bytes of memory. This is different than other languages like C and C++, which typically store character values using just a single bite. As we'll see, in a moment since Rust stores characters using four bites and Unicode we can represent much more than just simple letters and numbers. We create a Char literal in Rust by enclosing the character in single quotes as shown here. The code on line 2 creates a new Char representing the letter a and assigns it to the variable, named letter. And below that on line 3 we create another Char for the number one and assign it to the variable named number. It's important to realize that representing the character one here with the Char data type is very different than representing the value of one with a numeric data type, such as an integer. We cannot apply arithmetic operations like addition and subtraction to the character representation of one like we would with an integer or floating point value. Now, as I mentioned earlier Rust Char's are stored as Unicode, which opens up a wide range of characters beyond letters and numbers including this collection of miscellaneous symbols. Let's try to create a Char in our Rust program to represent this upward pointing finger, which corresponds to the hexadecimal character code 261D. We can specify a Char using its Unicode value by using slash U and then putting the hexadecimal value, in curly braces, 261D. Now that we've declared three characters let's use a print macro to display them all to the console. Notice that I'm using the slash in sequence here to insert a new line between each of the characters. Now when I run this program, we can see the output with the letter a, the number one and the finger symbol. Something to keep in mind is that not all environments will be able to display some of the more exotic Unicode characters. The VS code editors built in terminal is able to display the pointing finger. But if I try to run that same program from the Windows command prompt we get the letter a and the one but the finger is replaced by a box with a question mark because the command prompt cannot display that character.

Contents