Rust By Example: Primitives

Опубликовано: 09 Январь 2025
на канале: Stephen Blum
127
4

Variables in Rust can take on different forms: numbers, letters, and more. We call these scalar types. For example, we have integers with labels like i8, i16, i32, i64 to indicate their size.

A signed integer, positive and negative, has a size limit too, with 255 for i8,or for example, 65,535 for i16. Rust provides unsigned integers for when you need only positive values, taking full advantage of the maximum value of the integer. On the other hand, if your signed integer is negative, your smallest number could be as low as negative 2.14 billion.

We also have floating-point numbers, like float32 and float64, for decimal values. We also have char for alphanumeric variables including emoticons and emojis. Booleans, or bool, represent true or false, whereas we also have an empty type, kind of like null in other languages.

In Rust, you can also group together different scalar types in lists through compound types like arrays and tuples. These are foundational types which are usually enough for most programming needs. When defining variables in Rust, you can annotate them with i32 or bool, even though Rust can figure out the type for you.

Defining variables is flexible; you can use just '12', or you can use a suffix like 128i32 or 64u to define it further. If you want to change the value of a defined variable, you have to add 'mut' before it. Be careful, though, as Rust does not allow you to change the type of a variable once defined.

A unique feature that Rust offers is variable shadowing which allows you to redefine a variable within an inner scope. This, however, can be confusing and may lead to messy code in practice.