我如何使这个编译:
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?)
}错误消息:
--> 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发布于 2022-07-16 19:45:12
您不必在闭包中使用变形结构 S,因为这会移动字符串。
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比较String,s,从&str到&str,cmp。
// Automatically dereferenced
x.s == cmp手工操作:
// Manually dereferenced. You don't have to do this for structs.
(**x).s进一步阅读
https://stackoverflow.com/questions/73006818
复制相似问题