Stone
Stone

Reputation: 291

How do I avoid "cannot move out of static item" when using a lazy_static variable?

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.

Upvotes: 4

Views: 2796

Answers (1)

Shepmaster
Shepmaster

Reputation: 430368

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

fn main() {
    &STRING;
}

See also:

Upvotes: 5

Related Questions