I have a mutable Option
type and I'm trying to mutate the thing inside the Some
but I can't figure out how to do it.
use std::net::TcpStream;
use std::io::Write;
struct Foo {
stream: Option<TcpStream>,
}
impl Foo {
fn send(&mut self) {
self.stream.map(|x| x.write(b"test")).expect("Couldn't write");
}
}
This produces the error:
error[E0596]: cannot borrow immutable argument `x` as mutable
--> src/main.rs:10:29
|
10 | self.stream.map(|x| x.write(b"test")).expect("Couldn't write");
| - ^ cannot borrow mutably
| |
| consider changing this to `mut x`
Can someone try to implement send
as an example to help me understand?
As Vladimir Matveev points out,
if let
is even nicer, and is more idiomatic than iterating over theOption
:Although I usually use
Option::as_mut
:Other options
As Vladimir Matveev points out (again!),
map
is usually used to transform data, not for side effects (which I agree with). You could instead useiter_mut
, as I feel that iteration is usually for side effects. I like this because it means our code can avoid having a conditional:You can also leverage
IntoIterator
:As a follow-up to @idupree's variant, it is also possible to use if-let syntax:
I'd also argue that this is more idiomatic than
map()
, becausemap()
method is intended for transforming anOption
, not executing side effects (and assignment is a side effect).You can match on the
Option
directly, like the following (showingi32
rather thanTcpStream
):(Not sure whether that's the most idiomatic way to do it.)