- 第1章:基础
Rust 生命周期
之所以引入这个概念主要是应对复杂类型系统中资源管理的问题。
引用是对待复杂类型时必不可少的机制,毕竟复杂类型的数据不能被处理器轻易地复制和计算。
但引用往往导致极其复杂的资源管理问题,首先认识一下垂悬引用:
fn main() {
let r; {
let x = 5; r = &x;
}
println!("r: {}", r);
}
fn main() {
fn longer(s1: &str, s2: &str) -> &str {
if s2.len() > s1.len() {
s2
} else {
s1
}
}
}
fn main() {
fn longer(s1: &str, s2: &str) ->&str {
if s2.len() > s1.len() {
s2
} else {
s1
}
}
let r;
{
let s1 = "rust";
let s2 = "ecmascript";
r = longer(s1, s2);
}
println!("{} is longer", r);
}
虽然这样并不能够改变引用的生命周期,但可以在合适的地方声明两个引用的生命周期一致。
生命周期注释用单引号开头,跟着一个小写字母单词:
fn main() {
fn longer < 'a > (s1: &'a str, s2: &'a str) -> &'a str {
if s2.len() > s1.len() {
s2
} else {
s1
}
}
}
fn main() {
fn longer < 'a > (s1: &'a str, s2: &'a str) -> &'a str {
if s2.len() > s1.len() {
s2
} else {
s1
}
}
let r; {
let s1 = "rust";
let s2 = "ecmascript";
r = longer(s1, s2);
println!("{} is longer", r);
}
}
fn main() {
struct Str < 'a > {
content: &'a str
} let s = Str {
content: "string_slice"
};
println!("s.content = {}", s.content);
}
fn main() {
struct Str < 'a > {
content: &'a str
} impl < 'a > Str < 'a > {
fn get_content(&self) -> &str {
self.content
}
}
let s = Str {
content: "string_slice"
};
println!("s.content = {}", s.content);
}
fn main() {
use std::fmt::Display;
fn longest_with_an_announcement < 'a,
T > (x: &'a str, y: &'a str, ann: T) -> &'a str where T: Display {
println!("Announcement! {}", ann); if x.len() > y.len() {
x
} else {
y
}}
longest_with_an_announcement("11","323",3);
}
网友评论0