Hey Guys !
I'm new here and recently I started to learn Rust and actually I love it !
Even the Rust book is really friendly and very understandable.
I'm using Rust with vscode I used to write code without semicolon and every time the IDE is shouting on me because I forgot to add the semicolon at the end.
Is there any extension that format/add the semicolon at the end or I should reacquired the semicolon habit (like in C and Java ) ?
Yes. Rust requires semicolons for a reason: syntactic ambiguity. It's not in general possible to guess where to insert semicolons, the programmer has to supply them to make statement boundaries clear.
Consider something like
let x = foo
(1 + 2)
should a semicolon be added at the end of the first line? It's not possible to know. The programmer has to know whether s/he meant to write a function call or two separate statements.
In some cases, if you forget one here or there, the compiler suggestions sometimes are good at pointing out where semicolons are needed. E.g.
fn main() {
let x = 1
let y = 2
}
error: expected `;`, found keyword `let`
--> src/main.rs:2:14
|
2 | let x = 1
| ^ help: add `;` here
3 | let y = 2
| --- unexpected token
error: expected `;`, found `}`
--> src/main.rs:3:14
|
3 | let y = 2
| ^ help: add `;` here
4 | }
| - unexpected token
Other than that, you’ll have to write them by hand; on the other hand, the line breaks you can leave up to the code formatter called “rustfmt” and usually called in the terminal via “cargo fmt”, or through the relevant shortcut with IDE integration, e.g. ctrl+shift+I on my machine, using the “rust-analyzer” extension.
Like, I can write
fn main(){let x=1;let y=2;}
and it turns into
fn main() {
let x = 1;
let y = 2;
}
for me.
Not that I’d do that a lot, but sometimes if a line becomes too long, or I move code around and the indentation changes, using rustfmt on your projects is super useful in that you don’t need to handle adjusting any of the whitespace and line breaks in those kind of situations yourself.