Is it possible to implement a trait for a closure without using auto trait?

Is there any way I can implelement a trait for a closure, without using auto trait feature? Something like this:

    let lambda = || {};
    impl Foo for type_of(lambda) {}

What I have come across
Inspired by the idea of thread safety implemented by Rust, I want to make GPU command "thread" safety as well, I wrote code like this:


auto trait GpuSync {}

struct Buffer {}

impl Buffer {
    pub fn render(&self) {}

impl ! GpuSync for Buffer {}

struct Queue {}

impl Queue {
    pub fn submit<F>(&mut self, f: F) where F: FnOnce(), F: GpuSync {

fn main() {
    let mut queue = Queue {};

    let buffer = Buffer {};

    queue.submit(move || {

it works perfect, the compiler will report an error saying that

within `[closure@src/ 29:6]`, the trait `GpuSync` is not implemented for `Buffer`

The only problem is that auto trait feature is not stable, I cannot use it in a stable version.

So is there any way I can manually implement GpuSync on the closure type [closure@src/ 29:6]?

Since the types of closures are not nameable, the only way to do this would be a blanket impl like impl<F: FnOnce()> GpuSync for F, but that's probably not going to help since (1) you'd have to repeat it for all possible signatures, and (2) it would also cover closures that you presumably don't want to be GpuSync.

1 Like

Another way of thinking, since closure is nameless, is there any way I can convert a closure to a struct type? For example:

    let i = 1;
    let lambda = move || {
    struct Lambda {
        i: i32,
    impl Lambda {
        pub fn run(&self) {}

There problem is that only the compiler knows the captures, If I can know it, than maybe I can use macros to do the conversion...

I'm pretty sure there's no clean/reliable way to do this.

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.