How to cast into trait object

Hi,
can I avoid the as-cast in the snippet below?
What is the easiest way to cast a value into a trait object?

struct S;
trait T {}
impl T for S {}

fn cast_as(s: S) -> Box<dyn T> {
    Box::new(s) as _
}

/* does not compile
fn cast_into(s: S) -> Box<dyn T> {
    Box::new(s).into()
}
/*

Just remove the as-cast

fn cast_as(s: S) -> Box<dyn T> {
    Box::new(s)
}

You can read more about how the compiler deals with type coercions here: Type coercions - The Rust Reference
Especially the unsize coercions part.

7 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.