为什么println!(foo.bar()?)移动foo?

bar() 的定义:

pub fn bar(self) -> Result<String>

编译器给了我一个错误:

println!("{}", foo.bar()?);
let deserialized = serde_json::from_str(&foo.bar()?)?; // Use of 'foo' after move

为什么println移动foo?当我将另一个变量绑定到 时foo.bar(),编译器很好。

编辑:这基本上就是我所拥有的

let res = reqwest::blocking::get(request_path)?;
println!("{}", res.text()?);
                   ------ `res` moved due to this method call
let deserialized = serde_json::from_str(&res.text()?)?;
                                         ^^^ value used here after move

回答

是什么让您认为 println 正在采取行动?bar明确说明它移动;你会得到同样的错误:

let x = foo.bar()?;
let y = foo.bar()?;  // Error, foo has been moved.

当我将另一个变量绑定到 foo.bar() 时,编译器很好。

因为现在您不再尝试foo再次使用。相反,您多次重用调用的返回值,这很好(也就是说,直到被移动!)。

  • @Jerry the `self`, that means it takes `self: Self`, aka takes the subject by value. `&self` would be `self: &Self` aka taking the subject by shared reference, and `&mut self` would be `self: &mut Self` aka taking the subject by unique reference.

以上是为什么println!(foo.bar()?)移动foo?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>