How do I declare an instance of one of my Rust structs as static? [duplicate]

馋奶兔 提交于 2019-12-28 19:31:10

问题


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.



来源:https://stackoverflow.com/questions/26771078/how-do-i-declare-an-instance-of-one-of-my-rust-structs-as-static

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!