Hello,
What is the difference between let a = true;
and let a: bool = true;
?
Thank you.
Hello,
What is the difference between let a = true;
and let a: bool = true;
?
Thank you.
They're same.
Why do you think there's a difference? You seem to have been using the language for at least months; you have recently asked a question about type inference and received detailed answers. I wonder what could possibly be unclear about something as trivial as a bool, after all of this?
Hello,
Thank you so much for your reply.
Its use depends on the taste of the programmer?
Yes, but for collaborative project it's important to apply single taste across entire codebase. For this reason it's often recommended to use style the rustfmt reommends. You can run cargo fmt
to format your code.
Hello,
Thank you so much for your reply.
I want to know which one is better and if both are the same then why the Rust-Lang creator make it?
Type signatures on variables have two main functions:
true
, the type is very obvious, so most Rust programmers would write let a = true;
rather than let a: bool = true;
let x = Default::default();
or let x = (1..3).collect();
, you’ll get a compilation error[1] that can be resolved by writing something like let x: Cell<i32> = Default::default();
or let x: Vec<i32> = (1..3).collect();
. Often there’s multiple options to make the type clear to the compiler, e.g. these two could also be made to work by writing let x = Cell::<i32>::default();
or let x = (1..3).collect::<Vec<i32>>();
, respectively.Like this one
error[E0282]: type annotations needed
--> src/main.rs:2:9
|
2 | let x = Default::default();
| ^
|
help: consider giving `x` an explicit type
|
2 | let x: /* Type */ = Default::default();
| ++++++++++++
or this one
error[E0282]: type annotations needed
--> src/main.rs:2:9
|
2 | let x = (1..3).collect();
| ^
|
help: consider giving `x` an explicit type
|
2 | let x: Vec<_> = (1..3).collect();
| ++++++++
respectively.. ↩︎