现在可能很多 developer 都没有看好或者还不了解 Rust。但是 Rust 天生优势预测他会有一个好的未来,毕竟在底层上还没有能和 C/C++ 对抗的语言。有时候作为 native developer 我们甚至没得选,不过今天 Rust 的确给了我们一个更多选择。其实我学习了他可能即使在以后工作中也未必能够用到,但是我想这毕竟让我感受新的语言,感受到编写底层应用苦与乐。
fn main() {
// println!("Hello, world!");
let x;
{
let y = 10;
x = &y;
}
println!("{}",x);
}
--> src/main.rs:13:9
|
13 | x = &y;
| ^^^^^^ borrowed value does not live long enough
14 | }
| - `y` dropped here while still borrowed
15 | println!("{}",x);
|
编译会报错,因为在 Rust 中 {} 是一个作用域,我们编译器会根据{}将其中不再使用变量 drop 也就是从内存中释放掉,因为 x 是使用了 y 的引用。所以当 y 内存被释放 x 也就是无法访问了。有点绕,对了不绕也不是native。
fn main() {
// println!("Hello, world!");
let x; //'a
{
let y = 10;//'b
x = &y;
}
println!("{}",x);
}
让我们进一步通过一个方法来看如何定义生命周期来解决问题
error[E0106]: missing lifetime specifier
--> src/main.rs:8:27
|
8 | fn pr(x: &str, y:&str) -> &str{
| ^ expected lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y`
问题是这里返回值是函数内部创建的,这里 x 和 y 可能来自不用作用域,所以返回值无法确保返回值的 x 或 y 的作用域是否还存在。
fn pr<'a>(x: &'a str, y:&'a str) -> &'a str{
if x.len() == y.len(){
x
}else {
y
}
}
通过添加声明周期,让参数生命周期保持一致,以防止放生在某个作用域结束就销毁了。
fn main() {
let a = "a string";
let b = "a string";
let c = pr(a,b);
println!("{}",c);
}