Rust is static typed language and we need to define data with the types. The above program works due to a concept called the type inference which is supported by Rust nicely.
When you assign an initial value to a variable, Rust will infer the initial value and based on it, it'll auto assign the default type good type. In following example, the type of x will be i32
as an integer.
fn main() {
let x: i32 = 12;
println!("{}", x);
}
We've few integer data types in Rust such as i8
, i16
, i32
, i64
, and i128
as signed integer and u8
, u16
, u32
, u64
and u128
as unsigned integer.
fn main() {
let x: u8 = 12;
println!("{}", x);
}
If the assigned value contains decimal point in it, it'll be treated as floating-point number and the default value will be f64
. For the float, we've f32
and f64
and f64
being the default one.
fn main() {
let x = 13.3;
println!("{}", x);
}
As usual, we've more primitive data types as we have found in other programming language such as char
for character with single character. The main difference in Rust that you'll notice is, you can have the UTF-8 character. The default and the only type for the character is char
.
fn main() {
let x = '🥳';
println!("{}", x);
}
Finally, the bool
or boolean is yet another primitive data type that has true
and false
as one of the possible values.
fn main() {
let x: bool = true;
println!("{}", x);
}
We've seen the string in double quotes. But, string is not the primitive data type in Rust. We'll talk about string in future.
Labels: rust