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);
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With