Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare the type of the variable in Rust for loops?

Tags:

rust

C++ example:

for (long i = 0; i < 101; i++) {     //... } 

In Rust I tried:

for i: i64 in 1..100 {     // ... } 

I could easily just declare a let i: i64 = var before the for loop but I'd rather learn the correct way to doing this, but this resulted in

error: expected one of `@` or `in`, found `:`  --> src/main.rs:2:10   | 2 |     for i: i64 in 1..100 {   |          ^ expected one of `@` or `in` here 
like image 415
Syntactic Fructose Avatar asked Jun 28 '14 04:06

Syntactic Fructose


People also ask

Can you declare a variable in a for loop?

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.

Which variable is used in for loop?

A common identifier naming convention is for the loop counter to use the variable names i, j, and k (and so on if needed), where i would be the most outer loop, j the next inner loop, etc. The reverse order is also used by some programmers.

Can variables be used to initialize the loop variable?

In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not.

HOW DO FOR loops work in Rust?

A for loop's expression in Rust is an iterator that ​returns a series of values. Each element is one iteration of the loop. This value is then bound to variable and can be used inside the loop code to perform operations.


1 Answers

You can use an integer suffix on one of the literals you've used in the range. Type inference will do the rest:

for i in 1i64..101 {     println!("{}", i); } 
like image 77
BurntSushi5 Avatar answered Sep 19 '22 01:09

BurntSushi5