如何将我的 Rust 结构之一的实例声明为静态? [英] How do I declare an instance of one of my Rust structs as static?

查看:34
本文介绍了如何将我的 Rust 结构之一的实例声明为静态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将自己的结构之一的实例声明为静态?此示例无法编译:

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

推荐答案

您不能在全局范围内调用任何非const 函数.通常,您可以执行结构体字面量之类的操作,但隐私规则可能会阻止您这样做,因为存在私有字段并且您没有在同一模块中定义它.

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,
}

你可以这样写:

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

...但这是你在真正的 staticconst 声明中得到的最好的结果.然而,有一些解决方法可以实现这种事情,例如 lazy-static,其中您的 Server::new() 完全合法.

… 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.

这篇关于如何将我的 Rust 结构之一的实例声明为静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆