The Rust Programming Language — Primitives — Numeric Types and Type Annotations
We cannot change type of the variable once it is assigned a value of a certain type. Rust compiler will throw an error if you assigned a variable a value of type Number and in subsequent lines, you reassign the variable with a value of String type.
Take for example below code snippet:
fn main() {
let mut x = 1.1;
x = "The quick brown fox...";
let y = 2.2;
println!("x times y is {}!", x*y);
}Compilation Output:


Once you define a value in rust, that value gets a particular type associated with itself and then the type of the value can’t be changed. You are not allowed to change the type at runtime.
Type Annotations
We can also define the types explicitly in Rust. It is very similar to TypeScript and there are bunch of Type Annotations available in Rust.
fn main() {
let x: f64 = 1.1;
let y = 2.2;
println!("x times y is {}!", x*y);
}f64 tells us explicitly that x is a floating number. It is not mandatory as Rust is perfectly capable to infer the types. Sometimes, for complex types, Rust says to be more explicit upfront.
And just like TypeScript, it is possible to pass types to almost everything.
fn main() {
let x = 1.1;
let y = 2.2;
let answer = multiply_both(x, y);
println!("x times y is {}!", answer);
}
fn multiply_both(x: f64, y: f64) -> f64 {
return x*y;
}Observations from above code:
- Return type of method is defined using an arrow
-> f64 - Parameters also can have a type
answerautomatically is inferred to be of typef64

There is a small catch…
While defining functions, you always have to define return type for parameters as well as it’s return types. It cannot be left to inference.
You can read above code as:
multiply_both takes 2 f64 arguments and returns an f64 argument.
Rust also does not have any type. So we can’t typecast stuff.
So, here we learnt about the Rust’s capability to assigh a type to vairable, type inference and also strictness of the compiler of Rust.
Please share the feedback about this article.
You can subscribe to my newsletter about The Rust Programming Language here. You can read about all the articles in this series here.
Rustaceans 🚀
Thank you for being a part of the Rustaceans community! Before you go:
- Show your appreciation with a clap and follow the publication
- Discover how you can contribute your own insights to Rustaceans.
- Connect with us: X | Weekly Rust Newsletter






