我再次遇到借阅检查员......
enum TcpOrStr {
AddTcp(TcpStream),
RmTcp(SocketAddr),
Str(String, SocketAddr)
}
fn main() {
let listener = TcpListener::bind("127.0.0.1", 5555);
// bind the listener to the specified address
let mut acceptor = listener.listen();
let (tx, rx) = channel();
spawn(proc() {
let mut streams: Vec<TcpStream> = Vec::new();
loop {
let rxd: TcpOrStr = rx.recv();
match rxd {
AddTcp(stream) => {
streams.push(stream);
}
RmTcp(src) => {
// FIXME: O(n) operation
streams.retain(|mut strm|{ return strm.peer_name().unwrap() != src});
}
Str(line, src) => {
for stream in streams.iter_mut() {
if stream.peer_name().unwrap() == src {
continue;
}
let mut line_vec = line.clone().into_bytes();
let _ = stream.write(line_vec.as_mut_slice());
}
}
}
}
});
错误是:
Compiling chat v0.1.0 (file:///home/chris/rust/chat)
src/chat.rs:29:55: 29:59 error: cannot borrow immutable dereference of `&`-pointer `*strm` as mutable
src/chat.rs:29 streams.retain(|mut strm|{ return strm.peer_name().unwrap() != src});
^~~~
error: aborting due to previous error
Could not compile `chat`.
我的错误是什么?
答案 0 :(得分:3)
传递给retain
中的谓词的参数永远不可变,但peer_name()
只能在可变对象上调用。
不确定那里有什么最佳解决方案。
http://doc.rust-lang.org/std/io/net/tcp/struct.TcpStream.html#method.peer_name
http://doc.rust-lang.org/std/vec/struct.Vec.html#method.retain