Skip to content

portable-atomic-util: Example for Arc<dyn Trait> #143

Closed
@piotrfila

Description

Hello,
I am trying to port a crate that uses Arc<dyn Trait> for dynamic dispatch to but I could not find a way to do this with this crate.
Minimal example:

trait MyTrait {
    fn do_stuff(&self, x: &mut u32);
}

struct Foo(u32);

impl MyTrait for Foo {
    fn do_stuff(&self, x: &mut u32) {
        *x = self.0;
    }
}

fn main()  {
    use portable_atomic_util::Arc;
    let arc = Arc::new(Foo(42)) as Arc<dyn MyTrait>;

    let mut x = 0;
    arc.do_stuff(&mut x);
}

The error I get: an 'as' expression can only be used to convert between primitive types or to coerce to a specific trait object.
This example works if use portable_atomic_util::Arc; is replaced with use alloc::sync::Arc;, though the latter is not available on my target architecture (thumbv6m),.
I also tried calling .into() and .try_into() on the Arc, as well as converting the Foo object like this:

    let arc = Arc::new(*(&Foo(42) as &dyn MyTrait));

but those methods work neither on this crate's Arc nor alloc's.

Is there a way to do this using this crate?

Metadata

Assignees

No one assigned

    Labels

    A-portable-atomic-utilArea: related to portable-atomic-util crateC-documentationCategory: related to documentation.S-blockedStatus: Blocked on something else

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions