#Lazy Static (once_cell) with functions

3 messages · Page 1 of 1 (latest)

honest swan
#

I'm just asking why can't I do this :

use once_cell::unsync::Lazy; // 1.18.0

pub static STATIC_TEST: Lazy<fn(usize) -> bool> = new(|| {
    |a| a > 5
});

I get the error :

Compiling playground v0.0.1 (/playground)
error[E0425]: cannot find function `new` in this scope
 --> src/lib.rs:3:51
  |
3 | pub static STATIC_TEST: Lazy<fn(usize) -> bool> = new(|| {
  |                                                   ^^^ not found in this scope
  |
help: consider importing one of these items
  |
1 + use autocfg::new;
  |
1 + use mio::unix::pipe::new;
  |
1 + use want::new;
  |

error[E0277]: `Cell<Option<fn() -> fn(usize) -> bool>>` cannot be shared between threads safely
   --> src/lib.rs:3:25
    |
3   | pub static STATIC_TEST: Lazy<fn(usize) -> bool> = new(|| {
    |                         ^^^^^^^^^^^^^^^^^^^^^^^ `Cell<Option<fn() -> fn(usize) -> bool>>` cannot be shared between threads safely
    |
    = help: within `once_cell::unsync::Lazy<fn(usize) -> bool>`, the trait `Sync` is not implemented for `Cell<Option<fn() -> fn(usize) -> bool>>`
    = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock`
note: required because it appears within the type `Lazy<fn(usize) -> bool>`
   --> /playground/.cargo/registry/src/index.crates.io-6f17d22bba15001f/once_cell-1.18.0/src/lib.rs:716:16
    |
716 |     pub struct Lazy<T, F = fn() -> T> {
    |                ^^^^
    = note: shared static variables must have a type that implements `Sync`

error[E0277]: `UnsafeCell<Option<fn(usize) -> bool>>` cannot be shared between threads safely
   --> src/lib.rs:3:25
    |
3   | pub static STATIC_TEST: Lazy<fn(usize) -> bool> = new(|| {
    |                         ^^^^^^^^^^^^^^^^^^^^^^^ `UnsafeCell<Option<fn(usize) -> bool>>` cannot be shared between threads safely
    |
    = help: within `once_cell::unsync::Lazy<fn(usize) -> bool>`, the trait `Sync` is not implemented for `UnsafeCell<Option<fn(usize) -> bool>>`
note: required because it appears within the type `OnceCell<fn(usize) -> bool>`
   --> /playground/.cargo/registry/src/index.crates.io-6f17d22bba15001f/once_cell-1.18.0/src/lib.rs:413:16
    |
413 |     pub struct OnceCell<T> {
    |                ^^^^^^^^
note: required because it appears within the type `Lazy<fn(usize) -> bool>`
   --> /playground/.cargo/registry/src/index.crates.io-6f17d22bba15001f/once_cell-1.18.0/src/lib.rs:716:16
    |
716 |     pub struct Lazy<T, F = fn() -> T> {
    |                ^^^^
    = note: shared static variables must have a type that implements `Sync`

But I am using once_cell::unsync and not the sync version
link to playground

gentle robin
honest swan
#

Oh I was wrong, I see that it works with once_cell::sync I thought that once_cell::unsync would mean more possibility but it is the opposite