[rust-dev] Storing Handle (for Select) in a collection causes a crash

Frank Huang me at nongraphical.com
Wed Apr 16 17:39:35 PDT 2014

Hello all,

I have two somewhat related questions to ask you fine folks. I'm trying to
implement something that selects on a variable number of receivers, which
can change during program execution. I've been attempting to do so by
making Handles to those receivers and storing the handles in a HashMap, but
this causes the program to crash when Select::wait() is called. For
example, here's a small case which illustrates the problem:

fn main() {
  let mut handles = HashMap::new();

  let (tx, rx): (Sender<int>, Receiver<int>) = channel();
  spawn(proc() {

  let select = Select::new();
  let mut h = select.handle(&rx);
  unsafe { h.add(); }

  handles.insert(h.id(), h);

  let id = select.wait();
  let handle = handles.get_mut(&id);
  let num = handle.recv();
  println!("num = {}", num);

The segmentation fault happens at the line "let id = select.wait()". I can
confirm that this happens on OSX and armhf. I can confirm that this also
happens with a Vec<Handle>. BTW thanks to mcpherrin on IRC for suggesting
the HashMap solution.

Second somewhat related question: why can't I write this?

fn main() {
  let mut v = Vec::new();
  // get last item
  let n = v.get_mut(v.len()-1);
  println!("item = {}", *n);

For this program, the compiler complains at the line with v.get_mut that
"cannot borrow `v` as immutable because is is also borrowed as mutable". Is
there another way to retrieve, mutably, the last element of a vector? (this
is relevant if I want to have a vector of Handles, since Handle::recv()
requires &mut self)

Thanks for your help!

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20140416/6712c4af/attachment.html>

More information about the Rust-dev mailing list