了解Rust中的Try_for_each吗?
我是Rust的新手,直到现在我很难理解编译器错误。在这种特定情况下,我有一个可犯错误的功能,我想应用于迭代器的每个元素。我尝试使用 try_for_each
,但编译器不断给我错误特征绑定():尝试不满足
。我不知道如何解决这个问题。我也想知道人们通常如何了解生锈错误,因为我觉得很难解码?
我的代码的结构如下
iter.try_for_each(|x| let some_var= fallible_function(*x)?; do_something_with_var(some_var);)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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 withfallible_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 likeResult::Ok
(you could return a Residual, https://doc.rust-lang.org/std/ops/trait.FromResidual.html, likeOption::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 returnOk(())
orSome(())
, depending on what the faillible function return.