Purpose of once_cell::sync::Lazy<String>?

Quoting: https://github.com/Pauan/rust-dominator/blob/master/examples/counter/src/lib.rs#L21-L25

         static ROOT_CLASS: Lazy<String> = Lazy::new(|| class! {
            .style("display", "inline-block")
            .style("background-color", "black")
            .style("padding", "10px")
        });

Quoting Lazy in once_cell::sync - Rust

A value which is initialized on the first access. This type is thread-safe and can be used in statics.

Can someone please enlighten me on:

  1. Why we need this to be Lazy<String> instead of regular String ?

  2. How once_cell::sync::Lazy differs from lazy_static!

  1. To get the type to be regular String, you must use only const fn to create the string. The only String that you can create with const fns is the empty string.
  2. Well, the once_cell crate doesn't rely on macros, so some people find it easier to understand. Otherwise there isn't really any difference.
4 Likes

Why is this? Is it because of the static ?

Yeah. The compiler evaluates the expression at compile time and hard-codes the resulting value in the executable. The expression must be const for it to be possible to evaluate it at compile time.

2 Likes

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.