了解Rust中的Try_for_each吗?

发布于 2025-02-07 02:20:28 字数 313 浏览 3 评论 0 原文

我是Rust的新手,直到现在我很难理解编译器错误。在这种特定情况下,我有一个可犯错误的功能,我想应用于迭代器的每个元素。我尝试使用 try_for_each ,但编译器不断给我错误特征绑定():尝试不满足。我不知道如何解决这个问题。我也想知道人们通常如何了解生锈错误,因为我觉得很难解码?

我的代码的结构如下

iter.try_for_each(|x| let some_var= fallible_function(*x)?; do_something_with_var(some_var);)

I am new to Rust and until now I have very hard time understanding the compiler errors. In this specific case I have a fallible function that I want to apply to every element of the iterator. I have try using try_for_each but compiler keeps giving me error the trait bound (): Try is not satisfied . I have no idea how to resolve this issue. I also wonder how people usually get idea of Rust errors, because I feel it is very hard to decode?

Structure of my code is as follows

iter.try_for_each(|x| let some_var= fallible_function(*x)?; do_something_with_var(some_var);)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橘和柠 2025-02-14 02:20:28

try_for_each取一个返回try类型的闭合/函数( https:https://// doc.rust-lang.org/std/ops/trait.trait.html ),喜欢选项或结果,您可以在其中应用运算符,就像您对 fallible_function(*x)?,因此,如果您的功能返回结果,则闭合必须返回结果,但是您的关闭结束却一无所有,因此您必须返回可算数的值,例如 result :: ok ok /code>(您可以返回残差, https:// doc。 Rust-lang.org/std/ops/trait.fromresidual.html ,喜欢 option :: none ,但是迭代器将在第一次迭代后始终返回)。

如果您想进一步了解它的内部工作,以及如何使您可以为高级制作自己的类型控制流我强烈建议您研究尝试性状,但是除此之外,您只需要返回 ok(())一些(()),取决于可疑功能的返回。

try_for_each take a closure/function that return a Try type (https://doc.rust-lang.org/std/ops/trait.Try.html), like Option or Result, where you can apply the ? operator, just like you did with fallible_function(*x)?, so if your function return an Result, the closure must return an Result, but your closure end with nothing, so you must return an Infaillible value like Result::Ok (you could return a Residual, https://doc.rust-lang.org/std/ops/trait.FromResidual.html, like Option::None, but the iterator will always return after the first iteration).

I'm entering a bit too much into the detail on how the ? operator work, if you want to know more about the inner working of it and how it can enable you to make your own types for advanced control flow I would highly suggest you to look into the Try trait, but other than that yeah you just need to return Ok(()) or Some(()), depending on what the faillible function return.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文