Variables: Difference between revisions

Line 4,648:
end
end</syntaxhighlight>
 
=={{header|Rust}}==
 
In Rust a variable needs to be declared before it is used. A variable is declared using the "let" command. Some common data types are: i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64, bool, char and String. Rust is strongly typed and strictly typed, however the Rust compiler can infer the data types based on how the variable is used. Therefore there are several different options for variable declaration:
<syntaxhighlight lang="rust">
let var01; // The compiler will infer the type or the compiler will ask for type annotations if the type can't be inferred
let var02: u32; // The compiler will check if a value is assigned to var02 before being used
let var03 = 5; // The compiler will infer the type or it will fallback to i32
let var04 = 5u8; // Initialization to unsigned 8 bit (u8) number 5
let var05: i8 = 5; // Type annotation + Initialization
let var06: u8 = 5u8; // Type annotation + Initialization
var01 = var05; // This line makes the compiler infer var01 should be a signed 8 bit number (i8).
var02 = 9u32; // Assigning to var02 after declaration
</syntaxhighlight>
Variables are immutable by default. So all the above declarations will all create an immutable variable that can't be reassigned once assigned for the first time. To make the variable mutable you need to add the "mut" keyword like in the following examples:
<syntaxhighlight lang="rust">
let mut var07;
let mut var08: f32;
let mut var09 = 1.5;
let mut var10 = 2.5f32;
let mut var11: f32 = 5.0;
let mut var12: f64 = 5.0f64;
var07 = var11; // This line makes the compiler infer var07 should be a f32.
var08 = 3.1416f32; // Assigning to var08 after declaration
var08 = 2.7183f32; // Reassigning var08 since it can be reassigned since it is mutable.
</syntaxhighlight>
The compiler emits a waring if a variable is not used. To suppress the warning, you need to put an underscore "_" prefix before the variable name:
<syntaxhighlight lang="rust">
let _notused = 10;
let mut _mutnotused = 42;
</syntaxhighlight>
 
=={{header|Scala}}==