Solved - Stuggling with lifetimes of wrapper struct of Arc and RwLock

Update:
@thepowersgang provided a working solution on the Rust Discord.

The solution entails breaking the lifetime in two, though I’ve yet to gain enough understanding to explain how this resolves the issue in detail. If anyone wants to elaborate that’d be great!

Here’s the working playground link for anyone interested:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ac84032186bccd60b8ff112df4b62474

Original post:

Hi,

I’m in the process of prototyping a basic platform abstraction API to allows easy interaction with various devices connected to a host machine. The architecture I’m attempting to implement essentially allows a platform structure to create and store various device instances, while lending them out to an application to borrow and use the devices via a device reference which is essentially a wrapped Arc<RwLock>, I’ve wrapped it like this to allow storing of generalized associated data in the same structure and to provide a cleaner API to the application.

However I’m running into a lifetime error that I just can’t get my head around at the moment.

I’ve uploaded a striped down version of what I’m trying to achieve, which produces the lifetime error I’m struggling to resolve: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=237c867363d5a70479b8f8159a73ecda

Any help or feedback would be greatly appreciated!

Thanks,
Jasper

Usually Rc/Arc is used to make things 'static, and Rc/Arc which is not 'static are not that much convenient to use compare to the plain references. Actually, they have all the downsides in the both worlds: 1. they need runtime cost of heap allocation and counter handling, but 2. they still cannot escape the lexical scope their lifetime is tied to.

I recommend to remove all 'd on your code, and let all your Devices own their resources

1 Like

In the non-striped down version of that code there’s a Platform struct that creates and maintains Devices, and lends them out as DeviceRefs. The implementation of a particular device is also unknown outside of the Platform struct that maintains it.

because of these other constraints the current architecture seemed more appropriate, though I could be misunderstanding. Code probably talks best if you want to provide an example?