async fn execute(&self, partition: usize) -> Result<Pin<Box<dyn BatchStream + Send + Sync>>>;
Asked
Active
Viewed 682 times
3
-
You don't need `Pin` for any async fn. The compiler does it automatically when needed. – Chayim Friedman Nov 09 '21 at 07:19
-
@ChayimFriedman You do need pins if you're returning boxed futures, because otherwise they can't be awaited in contexts that are themselves pinned. (The pinning _requirement_ is what the compiler inserts automatically.) For example, code in [this answer](https://stackoverflow.com/a/67400017/1600898) or [this answer](https://stackoverflow.com/a/68883807/1600898) does require the box contents to be explicitly pinned, otherwise it wouldn't compile. – user4815162342 Nov 09 '21 at 08:40
-
@user4815162342 Oh I didn't see it returns a stream – Chayim Friedman Nov 09 '21 at 08:57
-
@ken I believe the answer to your question is: yes, if you want to await it, you'll need to pin it. You can also return the box and let the caller pin it, but since you're returning a box anyway (so you're already allocating), there's no harm in replacing `Box::new()` with `Box::pin()` and thereby making the return value awaitable. The pin wrapper adds no run-time cost, it's a purely static construct. – user4815162342 Nov 09 '21 at 09:24
1 Answers
1
In general: No. If you have a function in the form async fn f() -> Box<dyn Trait>
, there is no need for Pin
.
However, returning a Future
or Stream
is a special case. So if BatchStream
is an alias, or supertrait, or just mimics the Stream
trait, then the Pin
is likely necessary for the return value to be useful.
See other Q&As that explain where Pin
is needed with Stream
s:

kmdreko
- 42,554
- 6
- 57
- 106