首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Rust中,如何在`iter_mut`上使用‘`find()’

在Rust中,如何在`iter_mut`上使用‘`find()’
EN

Stack Overflow用户
提问于 2022-07-16 18:42:37
回答 1查看 117关注 0票数 0

我如何使这个编译:

代码语言:javascript
复制
struct S {
    s:String
}

fn main() {
    let mut v:Vec<S>;
    let cmp = "asdf";
    v.iter_mut().find(|&&x| x == cmp);
    //                 ^^^
    //                 What to write here when using find on a iter_mut (and why?)
}

错误消息:

代码语言:javascript
复制
 --> src/main.rs:8:25
  |
8 |     v.iter_mut().find(|&&x| x == cmp);
  |                         ^-
  |                         ||
  |                         |expected due to this
  |                         types differ in mutability
  |                         help: you can probably remove the explicit borrow: `x`
  |
  = note: expected mutable reference `&mut S`
                     found reference `&_`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `asdf` due to previous error
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-16 19:45:12

您不必在闭包中使用变形结构 S,因为这会移动字符串。

代码语言:javascript
复制
struct S {
    s: String,
}

fn main() {
    let mut v: Vec<_> = vec![S { s: "Hello".into() }, S { s: "asdf".into() }];
    let cmp = "asdf";

    // Will be Option<&mut S>
    let _found = v.iter_mut().find(|x| x.s == cmp);
}

我在Vec中添加了两个项,因为您声明了v而没有定义它。注意,闭包只使用x,它是一个&&mut,但是您不必在任何地方显式地这样说,因为x将在闭包的正文中被取消引用。

表达式x.s == cmp比较Strings,从&str&strcmp

代码语言:javascript
复制
// Automatically dereferenced
x.s == cmp

手工操作:

代码语言:javascript
复制
// Manually dereferenced. You don't have to do this for structs.
(**x).s

进一步阅读

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73006818

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档