Declaring and Printing
Note that Rust is a strongly-typed language. Every variable has a type, and you can’t reassign variables of one type to values of another type.
Rust uses the let
keyword to declare variables.
The compiler can usually automatically figure out the type.
Surprisingly, these kinds of variables cannot be reassigned, so are arguably not true variables. They are immutable.
Perhaps to help work around this issue in a way that minimises bugs, Rust lets you redeclare variables. This is called shadowing. A new variable is created with the same name as a previous variable.
We can print variables using variable interpolation in strings. By surrounding a variable with brackets, its value is inserted into a string.
To declare mutable variables, variables you can actually change, use the mut
keyword.
To declare true constants (where the value is hardcoded at compile time), use const
.
Rust Scalar Types
You can specify the type of a variable if you need to. For example, to create an 8-bit integer variable:
Just specify the type after a colon, after the variable name.
Rust has ten integer types. They are:
Signed: i8, i16, i32, i64 and i128
Unsigned: u8, u16, u32, u64, u128
The numbers here refer to the number of bits the variable occupies.
There are two floating-point types: f32
and f64
.
We also have a boolean type:
And there is a Unicode character type. We can specify characters in single quotes.
John - I spent ages teaching myself Borland C back in the 90s on a black and white laptop I bought for 700 quid! Back then there were no really good tutorials (such as yours!) and I struggled with those infernal pointers back then!