Rust 新手编译错误(对于 | ^ 中的 (key: String, value: String) 需要 `)`、`,`、`@` 或 `|` 之一)

问题描述 投票:0回答:1

我刚刚读完 Rust 编程语言的前三章,目前正在尝试在 YouTube 教程的帮助下应用我有限的知识构建 CLI 天气应用程序。

我大多不知道自己在做什么,只是想做一些东西来激发学习动力。

有人可以分享一些关于我做错了什么的解释吗?

我尝试编译 Rust 代码,但因语法错误而失败。

fn main() {
    for (x: String, ) in [("hello".into(),)] {}
}
error: expected one of `)`, `,`, `@`, or `|`, found `:`
 --> src/main.rs:2:11
  |
2 |     for (x: String, ) in [("hello".into(),)] {}
  |           ^ expected one of `)`, `,`, `@`, or `|`

error: could not compile `forecast` (bin "forecast") due to 1 previous error

游乐场

string rust compilation
1个回答
0
投票

有人可以分享一些关于我做错了什么的解释吗?

正如 Ivan C 所评论的,你不能在 inside 模式中拥有类型,这就是为什么

for
的左侧是
for
也不支持类型注释(正如您在上面的链接中可以看到或看不到),因此,如果您将代码更新为例如在
let
中找到的内容:

for (x,): (String,) in [("hello".into(),)] {}

你将会得到

  |
2 |     for (x,): (String,) in [("hello".into(),)] {}
  |             ^ --------- specifying the type of a pattern isn't supported

有两种解决方案:

  1. 确保输入值,您可以使用

    "hello".into()
    String::from("hello")
    ,而不是使用
    "hello".to_string()
    ,这将确保正确输入值并解决问题

  2. 使用迭代器,因为它们采用函数,可以输入:

    [("hello".into(),)].into_iter().for_each(|(x,): (String,)| {})
    

我个人推荐前者。

或者实际上您可以迭代

&str
本身,它工作得很好,并且仅在需要时才转换为
String

© www.soinside.com 2019 - 2024. All rights reserved.