How do I declare an instance of one of my Rust str

2019-01-20 14:51发布

问题:

This question already has an answer here:

  • How can you make a safe static singleton in Rust? 2 answers
  • How do I create a global, mutable singleton? 1 answer

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);
}

回答1:

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.