Skip to content

Conversation

@AaronErhardt
Copy link
Contributor

In some cases, it is useful to have access to an object (or widget) as a static variable. Unfortunately, the thread_local API of the standard library is pretty inconvenient and requires a couple of lines of boilerplate to setup a convenient wrapper function.

This new macro simplifies this process. Of course it's really not the most important thing to have, but I wanted to submit a PR here first instead of making this only available in Relm4.

::std::thread_local!(static THREAD_LOCAL_OBJ: #ty = #init_stream);

pub fn #name() -> #ty {
THREAD_LOCAL_OBJ.with(|w| w.clone())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not use something from once_cell here? Then you wouldn't have to export a function but could export a value that derefs to the object

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wow, that actually works 😅. Because unsync::Lazy::new is const you can use it in global const variables. I wasn't aware that you could use non-Send values in global constants, but that seems to work pretty well actually. I guess this makes this PR rather obsolete then...

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yay, less code :)

}
}

impl ToTokens for ThreadLocalObjectTokens {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could also just be a declarative macro in the glib crate or not? :) Having it as a proc-macro just complicates things

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants