owned this note
owned this note
Published
Linked with GitHub
---
tags: async, rustc
---
# Static async fns in traits tests
Example #1 (trivial example implementing for primitive type)
```rust
// check-pass
trait MyTrait {
async fn foo(&self) -> i32;
}
impl MyTrait for i32 {
async fn foo(&self) -> i32 {
*self
}
}
```
Example #2 (needs async fn)
```rust
trait MyTrait {
async fn foo(&self) -> i32;
}
impl MyTrait for i32 {
fn foo(&self) -> i32 {
// ~^ ERROR: async fn
*self
}
}
```
Example #3 (needs async fn, can't fake it like this)
```rust
trait MyTrait {
async fn foo(&self) -> i32;
}
impl MyTrait for i32 {
fn foo(&self) -> impl Future<Output = i32> { {
// ~^ ERROR: async fn
async {
*self
}
}
}
```
Example #4 (generics):
```rust
// check-pass
trait MyTrait<T, U> {
async fn foo(&self) -> &(T, U);
}
impl<T, U> MyTrait<T, U> for (T, U) {
async fn foo(&self) -> &(T, U) {
self
}
}
```
Example #5 (generics + bounds):
```rust
// check-pass
use std::fmt::Debug;
use std::hash::Hash;
trait MyTrait<T, U> {
async fn foo(&self) -> &(T, U) where T: Debug + Sized, U: Hash;
}
impl<T, U> MyTrait<T, U> for (T, U) {
async fn foo(&self) -> &(T, U) {
self
}
}
```
Example #6 (lifetimes):
```rust
// check-pass
trait MyTrait<'a, 'b, T> {
async fn foo(&'a self, key: &'b T) -> (&'a Self, &'b T);
}
impl<'a, 'b, T, U> MyTrait<'a, 'b, T> for U {
async fn foo(&'a self, key: &'b T) -> (&'a U, &'b T) {
(self, key)
}
}
```
Example #7 (lifetimes + bounds):
```rust
// check-pass
use std::fmt::Debug;
trait MyTrait<'a, 'b, T> {
async fn foo(&'a self, key: &'b T) -> (&'a Self, &'b T) where T: Debug + Sized;
}
impl<'a, 'b, T, U> MyTrait<'a, 'b, T> for U {
async fn foo(&'a self, key: &'b T) -> (&'a U, &'b T) {
(self, key)
}
}
```
Example #8 (associated types)
```rust
use std::fmt::Debug;
trait MyTrait<'a, 'b, T> where Self: 'a, T: Debug + Sized + 'b {
type MyAssoc;// = (&'a T, &'b U);
async fn foo(&'a self, key: &'b T) -> Self::MyAssoc;
}
impl<'a, 'b, T: Debug + Sized + 'b, U: 'a> MyTrait<'a, 'b, T> for U {
type MyAssoc = (&'a U, &'b T);
async fn foo(&'a self, key: &'b T) -> (&'a U, &'b T) {
(self, key)
}
}
```
Example #9 (you can fake it with an assoc type)
```rust
// check-pass
trait MyTrait {
type Fut<'a>: Future<Output = i32>
where
Self: 'a;
fn foo(&self) -> Fut;
}
impl MyTrait for i32 {
type Fut<'a> = impl Future + 'a
where
Self: 'a;
fn foo<'a>(&'a self) -> Fut<'a> {
async {
self
}
}
}
```
Example #10 (Use desugared version in both places)
```rust
trait MyTrait {
type Fut<'a>: Future<Output = i32>
where
Self: 'a;
async fn foo(&self) -> Fut;
}
impl MyTrait for i32 {
type Fut<'a> = impl Future + 'a
where
Self: 'a;
fn foo<'a>(&'a self) -> Fut<'a> {
// ~^ ERROR async fn
async {
self
}
}
}
```