what is a lazystatic macro with a post-processed string?

Splitting up the variables makes it easier to visualize:

lazy_static! {
  static ref select_kasten_by_title_sql: &'static str = {
    let tmp = str::replace(
      include_str!("sql/select_kasten_by_parameter.sql"),
      "QUERYPARAMETER",
      "zettlen.title",
    );
    tmp.as_str()
  };
}

tmp is a local variable that is owned by the block scope. You are trying to return a reference to tmp – you are trying to return a value that is referencing data owned by the current scope. This is not possible, as the compiler will tell you:

error[E0515]: cannot return value referencing local variable `tmp`
  --> src/main.rs:11:5
   |
11 |     tmp.as_str()
   |     ---^^^^^^^^^
   |     |
   |     returns a value referencing data owned by the current function
   |     `tmp` is borrowed here

A simple fix is to return the String directly, instead of a reference to it:

lazy_static! {
  static ref select_kasten_by_title_sql: String = str::replace(
    include_str!("sql/select_kasten_by_parameter.sql"),
    "QUERYPARAMETER",
    "zettlen.title"
  );
}

If you really, really want to return a &'static str, you can use Box::leak. I am not recommending you do this, because it provides no benefit over a String, but it is an option:

lazy_static! {
  static ref T: &'static str = {
    let tmp = str::replace(
      include_str!("sql/select_kasten_by_parameter.sql"),
      "QUERYPARAMETER",
      "zettlen.title",
    );
    Box::leak(tmp.into_boxed_str())
  };
}
``

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top