Start learning free

LESSON 10 OF 348 · VARIABLES

Data Types in Rust in Rust

Lesson

TL ; DR:

In Rust, not all data is treated the same. There are different data types, such as:

  • i32 - represents integer numbers like 3 and -12

  • f64 - represents floating point numbers like 3.14

  • &str - represents a string (sequence of characters) like "John Doe"

  • bool - represents a boolean, data that can have one of two values: true or     false

  • char - represents a single character like 'a', 'Z' or '?'



Full lesson:

One instruction can have several distinct meanings depending on the data types it's working with.

For example, suppose you see this line of code somewhere in a program:

println!("{}", a + b);

Can you tell for sure what it does without knowing anything about the variables a and b?

It might add two numbers, if a and b are both numbers:

let a: i32 = 10;
let b: i32 = -5;

println!("{}", a + b); // Output: 5

But it also might concatenate two strings, if a and b are both strings:

let a = String::from("Hello ");
let b = "world!";

println!("{}", a + b); // Output: Hello world!

Of course, addition and string concatenation are two completely different operations and Rust needs to figure out which one to do.

And this is exactly why Rust assesses the data type of every value you use in your program. In order to be able to make these decisions when needed.

In our example, when it reads a + b, Rust checks the data type of a and b. If both are strings, it performs string concatenation. If both are numbers, it performs addition.


Invalid operations:

Asessing data types is also helpful for Rust to make sure that what you do with the data actually makes sense.

For example, computers can perform mathematical operations on numbers, but not on strings. Of course, nobody can stop you from writing a program like this:

let a = "peanut";
let b = "butter";

println!("{}", a * b); // compile error

But when you try to run this program, Rust will throw a TypeError: bad operand types for binary operator '*'.

This is the way of Rust telling you: "Hey, I'm a little confused. How do you multiply two strings? I've never heard of that."


No null: Option, and String vs &str:

Rust has no null. A value that might be absent is an Option<T> — either Some(x) (a value) or None (nothing). Also note Rust's two string types: an owned, growable String versus a borrowed slice &str; and integers are sized, like i32.

let maybe_age: Option<i32> = Some(10);
let nothing: Option<i32> = None;

let owned: String = String::from("John");  // owned String
let borrowed: &str = "Doe";                // borrowed &str

Assignment
Follow the Coding Tutorial and let's practice with data types!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    Data Types in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free