4

I want to initialize a variable globally, so I used a package called lazy_static.

lazy_static::lazy_static! {
    static ref STRING: String = String::from("Hello, World");
}

fn main() {
    STRING;
}
error[E0507]: cannot move out of static item `STRING`
 --> src/main.rs:6:5
  |
6 |     STRING;
  |     ^^^^^^ move occurs because `STRING` has type `STRING`, which does not implement the `Copy` trait

I don't want to implement the Copy trait, I want to use same reference all over the application, like a 'static lifetime.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Stone
  • 241
  • 1
  • 4
  • 18
  • Aside: do you really want a `String` here? Perhaps `static STRING: &'static str = "Hello, world";` (no need for `lazy_static`) will suffice? Indeed, in that case, it could even be `const`. – eggyal May 26 '21 at 14:56

1 Answers1

5

Don't try to use the variable by value, use it by reference.

fn main() {
    &STRING;
}

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366