Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
}
like image 676
Bruce Avatar asked Nov 06 '14 03:11

Bruce


People also ask

How do I make an instance of a struct in Rust?

We create an instance by stating the name of the struct and then add curly brackets containing key: value pairs, where the keys are the names of the fields and the values are the data we want to store in those fields. We don't have to specify the fields in the same order in which we declared them in the struct.

What does&'static mean in Rust?

A static item is similar to a constant, except that it represents a precise memory location in the program. A static is never "inlined" at the usage site, and all references to it refer to the same memory location. Static items have the static lifetime, which outlives all other lifetimes in a Rust program.

What does static lifetime mean Rust?

Reference lifetime. As a reference lifetime 'static indicates that the data pointed to by the reference lives for the entire lifetime of the running program. It can still be coerced to a shorter lifetime.

Can structs have functions Rust?

Rust uses a feature called traits, which define a bundle of functions for structs to implement. One benefit of traits is you can use them for typing. You can create functions that can be used by any structs that implement the same trait.


1 Answers

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.

like image 87
Chris Morgan Avatar answered Nov 08 '22 16:11

Chris Morgan