Skip to content

#[cast_to] on trait impl block doesn't work when trait has associated types #4

@yume-chan

Description

@yume-chan

When a target trait has associated types, #[cast_to] attr causes compile errors when being used on the impl block:

use std::any::Any;

use intertrait::{cast::CastBox, cast_to};

trait MyTrait {
    type Output;

    fn create(&self) -> Self::Output;
}

struct Foo;

#[cast_to]
impl MyTrait for Foo {
    type Output = i32;

    fn create(&self) -> Self::Output {
        42
    }
}

cargo build output:

error[E0191]: the value of the associated type `Output` (from trait `MyTrait`) must be specified
  --> src\main.rs:26:10
   |
18 |         type Output;
   |         ------------ `Output` defined here
...
26 |     impl MyTrait for Foo {
   |          ^^^^^^^ help: specify the associated type: `MyTrait<Output = Type>`

But it works when attaches to struct block with associated types manually added:

#![feature(option_result_unwrap_unchecked)]

use std::any::Any;

use intertrait::{cast::CastBox, cast_to};

trait MyTrait {
    type Output;

    fn create(&self) -> Self::Output;
}

#[cast_to(MyTrait<Output = i32>)]
struct Foo;

impl MyTrait for Foo {
    type Output = i32;

    fn create(&self) -> Self::Output {
        42
    }
}

fn main() {
    let value: Box<dyn Any> = Box::new(Foo);
    let casted = unsafe { value.cast::<dyn MyTrait<Output = i32>>().unwrap_unchecked() };
    println!("{:?}", casted.create());
}

cargo run output:

   Compiling rust-test v0.1.0 (D:\dev\rust-test)
    Finished dev [unoptimized + debuginfo] target(s) in 1.02s
     Running `target\debug\rust-test.exe`
42

I'm using another macro to generate the trait impl block, so I prefer to also generate the #[cast_to] attr.

dependencies:

[dependencies]
intertrait = "0.2.1"
linkme = "0.2.0"

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions