A question about the boolean types

Hello,
What is the difference between let a = true; and let a: bool = true;?

Thank you.

They're same.

1 Like

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.

1 Like

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:

  • They can serve as documentation, to make code easier to read. Most of the time the programmer wants to know the type of variables in order to understand code, and in cases where the type isn’t obvious, adding the signature can make the code easier to understand. For the expression true, the type is very obvious, so most Rust programmers would write let a = true; rather than let a: bool = true;
  • If the type of an expression is ambiguous, the type signature can resolve the ambiguity. For example with something like 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.

  1. 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.. ↩︎

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.