Rust, Software Development

How To Declare And Use Variables In Rust

Rust Lang
Photo by Mark Vegera from Pexels

Variables in Rust are similar to variables in other high-level programming languages, and how we declare and use them are pretty straight-forward. There are several types of variables, and their declaration may differ from each other.

Types Of Variables In Rust

A variable can be a global variable, a local variable, a function parameter, or a struct field. As such, its declaration may require initialization at the same time.

Global Variable

A variable is a global variable when we declare it outside of any code blocks with the static keyword. We need to specify both the data type and value when we declare the variable.

Local Variable

If we declare it inside a function, it is typically a local variable, and the data type may be optional in Rust.

It can also be part of a for loop. In this case, we cannot specify its data type.

Function Parameter

If we declare a variable as part of a Rust function definition, it is a function parameter. We need to specify its data type.

Struct Field

A variable declared in a struct is a struct field. We only need to specify its data type. However, when we instantiate the struct Person, we need to specify appropriate values for the fields

Declare A Variable With Valid Name

When naming a variable, we can use letters, digits, and the underscore character. However, it must start with either a letter or an underscore. Moreover, a variable name with lowercase letters is different from a variable with uppercase letters because Rust is case-sensitive.

Declare And Assign Value In Rust

A variable in Rust can have an initial value when we declare it. But it depends on where we declare and how we use the variable. We can also assign it value after its declaration, but it depends if it is a mutable or immutable variable. By default, all variables are immutable in Rust.

For instance, these codes will fail compilation.

To declare a mutable variable in Rust, we use the mut keyword.

Using Variables

Although not immediately apparent when using Rust’s scalar primitive types, values have ownership and can change owners – from one variable to another. For example, these codes build and run successfully:

However, these will not compile:

Declaring and using variables are pretty much straight-forward until we start using custom data types. Then, we will have to deal with ownership and lifetimes.

This post is now part of Rust Programming Language For Beginners Tutorial.

You Might Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *