0

The signatures for Sender::send and JoinHandle::join are, respectively:

pub fn send(&self, t: T) -> Result<(), SendError<T>>
pub fn join(self) -> Result<T, Box<dyn Any + Send + 'static>>

Since SendError implements Send and Any and owns its content, this should work:

pub fn finish(
    tx: std::sync::mpsc::Sender<()>,
    jh: std::thread::JoinHandle<()>,
) -> Result<(), Box<dyn std::any::Any + Send + 'static>> {
    tx.send(())?;
    jh.join()?;
    Ok(())
}

but it fails with the trait From<SendError<()>> is not implemented for Box<dyn Any + Send>.

Why is there a constraint failure and how does the function signature need to change to have it compile?

Would like to not use external libraries.

1
  • 1
    It may be better to unwrap the result of calling join. This will only be Err if the thread panicked, and in that case it may make more sense to propagate the panic as a panic anyway. Commented Jan 27 at 20:55

1 Answer 1

0

You can do it explicitly by wrapping the error in a Box (giving concrete type Box<SendError>) and then decaying it to Box<dyn Any> with an explicit as cast:

pub fn finish(
    tx: std::sync::mpsc::Sender<()>,
    jh: std::thread::JoinHandle<()>,
) -> Result<(), Box<dyn std::any::Any + Send + 'static>> {
    tx.send(()).map_err(|e| Box::new(e) as Box<_>)?;
    jh.join()?;
    Ok(())
}
Sign up to request clarification or add additional context in comments.

3 Comments

I tried adding .map_err(Box::new), but didn't cast. What's happening with this cast?
@twig-froth you need to induce a coercion, the as is doing the work of coercing a Box<SendError<()>> into a Box<dyn Any + Send>
@twig-froth For what it's worth I have a lot of experience with Rust and I still find it confusing the Rust compiler doesn't infer and coerce the right thing automatically here without the explicit as cast.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.