Expressions, Values, and Types

Here is a statement that will govern a lot of our time in Rust. Let’s explore what this means:

An expression is evaluated to a value of a specific type

A lot of the work we do in programming is producing and using values. Values can be something like the number 9, true, the words “Hello world”, and more. Your computer will end up storing these values somewhere in memory, and then you’ll use them in things like calling functions or macros.

Each and every value you produce will have a type. Types help the computer know how much space to set up in memory to hold a value. But they also help out the programmer a lot by making sure we don’t do stupid things. For example, types help prevent us from trying to add the number 5 and the string “banana” together.

The way we produce values in Rust is with expressions. There are many different kinds of expressions, and we’ll learn about them throughout this course. An expression is a recipe that you, the programmer, give to the computer for how to produce a value.

Let me give you some examples. The expression 3 + 4 says “computer, please add the numbers 3 and 4 together to make a new value.” The expression apples * 2 says, “get the value contained in the variable named apples and multiply it by the number 2.” Here’s another interesting one: the expression 5 says “hey, give me the number 5.” That’s called a literal, which means that it’s an expression that doesn’t need to be evaluated into a value. And finally, add(7, 8) is an expression that says, “Call the function add on the values 7 and 8."

More complex expressions can be built up by combining simpler expressions. For example, we can combine the ideas above with:

add(3 + 4, apples * 2)

Instead of using the literal number 7 as the first parameter to the add function, we can provide our own expression, 3 + 4. Instead of the number 8, we can say apples * 2. Assuming the variable apples has the number 4 in it, these two expressions mean exactly the same thing.

The process of turning an expression into a value is called evaluation. You can think of the expression above as a tree:

Get hands-on with 1400+ tech skills courses.