Movatterモバイル変換


[0]ホーム

URL:


static

Keywordstatic 

Source
Expand description

A static item is a value which is valid for the entire duration of yourprogram (a'static lifetime).

On the surface,static items seem very similar toconsts: both containa value, both require type annotations and both can only be initialized withconstant functions and values. However,statics are notably different inthat they represent a location in memory. That means that you can havereferences tostatic items and potentially even modify them, making themessentially global variables.

Static items do not calldrop at the end of the program.

There are two types ofstatic items: those declared in association withthemut keyword and those without.

Static items cannot be moved:

staticVEC: Vec<u32> =vec![];fnmove_vec(v: Vec<u32>) -> Vec<u32> {    v}// This line causes an errormove_vec(VEC);

§Simplestatics

Accessing non-mutstatic items is considered safe, but somerestrictions apply. Most notably, the type of astatic value needs toimplement theSync trait, ruling out interior mutability containerslikeRefCell. See theReference for more information.

staticFOO: [i32;5] = [1,2,3,4,5];letr1 =&FOOas*const_;letr2 =&FOOas*const_;// With a strictly read-only static, references will have the same addressassert_eq!(r1, r2);// A static item can be used just like a variable in many casesprintln!("{FOO:?}");

§Mutablestatics

If astatic item is declared with themut keyword, then it is allowedto be modified by the program. However, accessing mutablestatics cancause undefined behavior in a number of ways, for example due to data racesin a multithreaded context. As such, all accesses to mutablestaticsrequire anunsafe block.

When possible, it’s often better to use a non-mutablestatic with aninterior mutable type such asMutex,OnceLock, or anatomic.

Despite their unsafety, mutablestatics are necessary in many contexts:they can be used to represent global state shared by the whole program or inextern blocks to bind to variables from C libraries.

In anextern block:

unsafe extern"C"{staticmutERROR_MESSAGE:*mutstd::os::raw::c_char;}

Mutablestatics, just like simplestatics, have some restrictions thatapply to them. See theReference for more information.


[8]ページ先頭

©2009-2026 Movatter.jp