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

Quoting: rust-dominator/lib.rs at master · Pauan/rust-dominator · GitHub

         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.

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.


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.