rust - 是否可以在 Rust for 循环中声明变量的类型?

标签 rust

C++ 示例:

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

我在 Rust 中尝试过:

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

我可以轻松地在 for 循环之前声明一个 let i: i64 = var 但我宁愿学习正确的方法来做这件事,但这导致了

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

最佳答案

您可以使用 integer suffix在您在该范围内使用的其中一个文字上。类型推断将完成剩下的工作:

for i in 1i64..101 {
    println!("{}", i);
}

关于rust - 是否可以在 Rust for 循环中声明变量的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47377094/

相关文章:

rust - 无法在另一种方法中使用迭代器,因为 "borrow might be used when that temporary is dropped"

rust - 一个数组如何包含对同一对象的多个可变引用?

types - PhantomData 和可变引用给出 "does not live long enough"错误

rust - Rust中具有HashMap拥有的节点的链接列表

testing - 测试子模块真的能减少 Rust 中的代码膨胀吗?

rust - 尽管看起来有效,但关联类型的生命周期限制被拒绝

rust - 如何匹配Some(&T)?

rust -::和 . 之间有什么区别?在使用rust ?

generics - 为什么 rust 只允许数组大小的独立常量?

rust - Tokio 的简单 TCP 回显服务器示例(在 GitHub 和 API 引用上)有什么好的详细解释?