How to declare an instance of one of the Rust structs as static?


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("", 23);

Best Solution

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.