問題一覧に戻る
中級ライフタイム
問題72: staticライフタイム
'staticはプログラム全体の期間続く特別なライフタイムです。文字列リテラルはプログラムバイナリに格納されるため'staticライフタイムを持ちます。グローバル定数やstaticも'staticライフタイムを持ちます。どのスコープよりも長生きする必要があるデータに有用です。Rustで最も長いライフタイムです。
// 文字列リテラルは'staticライフタイム
fn get_message() -> & str {
"Hello, Rust!"
}
// staticな参照
static GLOBAL: &str = "I am global";
fn make_static(s: & str) -> & str {
s
}
// const値も'static
const ERROR_MESSAGE: & str = "An error occurred";
fn main() {
let msg = get_message();
println!("{}", msg);
println!("{}", GLOBAL);
let static_str = make_static("This is static");
println!("{}", static_str);
}