ライフタイム
Rustの概念
code:.rs
{
let r; // ---------+-- 'a
// |
{ // |
let x = 5; // -+-- 'b |
r = &x; // | |
} // -+ |
// |
println!("r: {}", r); // |
} // ---------+
ある値のライフタイムが束縛する変数のライフタイムより短い場合,コンパイルが通らなくなる.
関数においてもライフタイムをケアした書き方が求められる場合がある
code:.rs
fn longest(x: &str, y: &str) -> &str { // コンパイル不可
if x.len() > y.len() {
x
} else {
y
}
}
返り値がxのライフタイムになるかyになるかが確定しない
ライフタイム注釈によって解決する
code:.rs
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
このように書くと'aがライフタイムを表し,うちもっとも短いものに合わせたものを返すということが明示される.
code:.rs
fn main() {
let string1 = String::from("long string is long");
let result;
{
let string2 = String::from("xyz");
result = longest(string1.as_str(), string2.as_str());
// ↑ borrowed value does not live long enough
}
println!("The longest string is {}", result);
}
ライフタイム省略規則に従っているパターンであればライフタイムの明示を省略できる