A confused problem about trait Future

I try to test a variables whether if satisfied trait Future, code as following:

use std::future::Future;
use ::core::marker::PhantomData;

fn val_implement<T> (_: T)-> bool {
//    println!("type of v: {:?}", type_of(v));
    trait SpecializedValue {
        fn value()-> bool { true }
    }
    impl<T: ?Sized> SpecializedValue for PhantomData<T>
        where  T: Future
    {}
    PhantomData::<T>::value()
}

async fn test_future_1()-> usize {
  200
}
fn test_future_2()-> impl Future {
    async {
        100
    }
}

fn main() {
    let f1 = test_future_1();
    let f2 = test_future_2();

    let is_future = val_implement(f1);
    let is_future = val_implement(f2);
}

But neither f1 nor f2 is compile error:

| pub struct PhantomData<T: ?Sized>;
| ---------------------------------- doesn't satisfy `PhantomData<T>: SpecializedValue`
|
= note: the method `value` exists but the following trait bounds were not satisfied:
        `<T as Future>`
        which is required by `PhantomData<T>: SpecializedValue`
         `T: Future`
        which is required by `PhantomData<T>: SpecializedValue`

when I delete the bounds of Future, it will be compiled success.

    impl<T: ?Sized> SpecializedValue for PhantomData<T>
//        where  T: Future
    {}

Why variables f1 and f2 are not satisfied trait Future even if I special its type impl Future ?

Please help, Thanks!

The val_implement method says that it can accept all types, even those that don't implement Future, but it then proceeds to try to use it in a way that requires T to be a Future. This is not allowed.

That you don't actually call val_implement with any non-futures doesn't matter. Generic code must be correct for all possible choices of generic arguments — not just those types you actually call it with.

The part about f1 and f2 is irrelevant because it's in a different function, but type checking happens locally per-function.

1 Like

Yes, I see, very thanks to you

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.