假设我有一个结构,其实现写入某处,即写入实现std::io::Write
特征的东西。但是,我不希望结构拥有它。以下代码有效:
fn main() {
let mut out = std::io::stdout();
let mut foo = Foo::new(&mut out);
foo.print_number(2);
}
struct Foo<'a> {
out: &'a mut dyn std::io::Write
}
impl<'a> Foo<'a> {
pub fn new(out: &'a mut dyn std::io::Write) -> Self {
Self {
out
}
}
pub fn print_number(&mut self, i: isize) {
writeln!(self.out, "The number is {}", i).unwrap()
}
}
但是,现在这个写作功能应该是可选的。我认为这听起来很容易,但现在以下内容无法编译:
fn main() {
let mut out = std::io::stdout();
let mut foo = Foo::new(Some(&mut out));
foo.print_number(2);
}
struct Foo<'a> {
out: Option<&'a mut dyn std::io::Write>
}
impl<'a> Foo<'a> {
pub fn new(out: Option<&'a mut dyn std::io::Write>) -> Self {
Self {
out
}
}
pub fn print_number(&mut self, i: isize) {
if self.out.is_some() {
writeln!(self.out.unwrap(), "The number is {}", i).unwrap()
}
}
}
因为:
error[E0507]: cannot move out of `self.out` which is behind a mutable reference
--> src/main.rs:20:26
|
20 | writeln!(self.out.unwrap(), "The number is {}", i).unwrap()
| ^^^^^^^^
| |
| move occurs because `self.out` has type `Option<&mut dyn std::io::Write>`, which does not implement the `Copy` trait
| help: consider borrowing the `Option`'s content: `self.out.as_ref()`
我不确定如何解释。
我尝试通过将相关行更改为:
writeln!(self.out.as_ref().unwrap(), "The number is {}", i).unwrap()
但后来我得到
error[E0596]: cannot borrow data in a `&` reference as mutable
--> src/main.rs:20:26
|
20 | writeln!(self.out.as_ref().unwrap(), "The number is {}", i).unwrap()
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
我真的不知道如何解释这些错误消息,令人惊讶的是,在没有真正理解的情况下,仅仅在随机的地方撒上&
s 和s 并没有真正到达任何地方!mut
(顺便说一句,我不确定这是否是解决这个问题的“好”方式?我对解决这个问题的完全不同的方法持开放态度,这基本上是可选地将要写入的内容传递到结构中,但没有拥有它的结构。我读到了Box
可能也相关的类型?)