8

How do I declare an instance of one of my own structs as static? This sample doesn't compile:

static SERVER: Server<'static> = Server::new();

fn main() {
    SERVER.start("127.0.0.1", 23);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Bruce
  • 461
  • 1
  • 8
  • 17

1 Answers1

16

You can’t call any non-const functions inside a global. Often you will be able to do something like struct literals, though privacy rules may prevent you from doing this, where there are private fields and you’re not defining it in the same module.

So if you have something like this:

struct Server<'a> {
    foo: &'a str,
    bar: uint,
}

You can write this:

const SERVER: Server<'static> = Server {
    foo: "yay!",
    bar: 0,
};

… but that’s the best you’ll get in a true static or const declaration. There are, however, workarounds for achieving this sort of thing, such as lazy-static, in which your Server::new() is completely legitimate.

mcarton
  • 27,633
  • 5
  • 85
  • 95
Chris Morgan
  • 86,207
  • 24
  • 208
  • 215