I've been trying to understand and play with futures
(version 0.3) but couldn't make this work. As I understand, a function is able to return a future of type A
only if the type A
implements the future trait. If I create a struct and implement the future trait, it's okay but why String
doesn't work?
use futures::prelude::*;
async fn future_test() -> impl Future<Output=String> {
return "test".to_string();
}
I get the error:
the trait bound `std::string::String: core::future::future::Future` is not satisfied
the trait `core::future::future::Future` is not implemented for `std::string::String`
note: the return type of a function must have a statically known sizerustc(E0277)
So I told myself, okay then I can use Box
like:
async fn future_test() -> impl Future<Output=Box<String>> {
return Box::new("test".to_string());
}
But the error is same:
the trait bound `std::string::String: core::future::future::Future` is not satisfied
the trait `core::future::future::Future` is not implemented for `std::string::String`
note: the return type of a function must have a statically known sizerustc(E0277)
What am I doing wrong? And why does the future hold the String
instead of the Box
itself?
async fn
automatically wraps the return type in a future for you, so you should change the signature to justasync fn future_test() -> String
. – apetranzillaasync fn hello() -> String { "hello".to_string() }
would compile to a function returningimpl Future<Output=String>
that will immediately complete when polled. – apetranzillaasync
qualifier. The function would then befn hell() -> impl Future<Output=String> { /* ... */ }
. The actual type implementingFuture
would be something you'd have to write by hand or import from another crate (likefutures
); the compiler has special support to generate futures fromasync fn
s that can't be fully replicated manually. – apetranzilla