Now that's a lot for me to digest. The term "covariance" is new to me, and I just had to look it up in the Rustonomicon. I'll need some time to process all that. I really have to read (and understand) more about variance first.
With those changes it works here!
That also works for me, and is much shorter. I also assumed if I do not mention any lifetime it would be 'static
, but it isn't. So that is good to know.
But when I combine it with my trait example, it does not work:
#![feature(type_alias_impl_trait)]
#![feature(generic_associated_types)]
use std::future::Future;
trait GetAnInteger {
type GetFuture<'a, 'b>: Future<Output = i32>; // NOTE: Could add `+ Sync` here
fn get<'a, 'b>(&'a self, offset: &'b i32) -> Self::GetFuture<'a, 'b>;
}
struct ManualGetAnInteger {
value: i32,
}
impl GetAnInteger for ManualGetAnInteger {
type GetFuture<'a, 'b> = std::future::Ready<i32>;
fn get<'a, 'b>(&'a self, offset: &'b i32) -> Self::GetFuture<'a, 'b> {
std::future::ready(self.value + *offset)
}
}
struct AutomaticGetAnInteger {
value: i32,
}
async fn some_async_stuff() {
println!("Let's pretend we do some async stuff here.");
}
impl GetAnInteger for AutomaticGetAnInteger {
type GetFuture<'a, 'b> = impl Future<Output = i32> + Send;
fn get<'a, 'b>(&'a self, offset: &'b i32) -> Self::GetFuture<'a, 'b> {
async {
// code might be added here in future
some_async_stuff().await;
// code might be added here in future
self.value + *offset
}
}
}
#[tokio::main]
async fn main() {
let getter1 = ManualGetAnInteger { value: 17 };
println!("Got value: {}", getter1.get(&100).await);
let getter2 = AutomaticGetAnInteger { value: 18 };
println!("Got value: {}", getter2.get(&200).await);
}
I get the following error:
error[E0700]: hidden type for `impl Trait` captures lifetime that does not appear in bounds
--> src/main.rs:30:30
|
30 | type GetFuture<'a, 'b> = impl Future<Output = i32> + Send;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
note: hidden type `impl Future` captures lifetime smaller than the function body
--> src/main.rs:30:30
|
30 | type GetFuture<'a, 'b> = impl Future<Output = i32> + Send;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
By the way, my rustc version is rustc 1.57.0-nightly (485ced56b 2021-10-07)
.