[易學易懂系列|rustlang語言|零基礎|快速入門|(5)]
Lifetimes
我們繼續談談生命周期(lifttime),我們還是拿代碼來說話:
fn main() {
let mut a = vec![1, 2, 3];
let b = &mut a; // &mut borrow of `a` starts here
// some code
println!("{:?}", a); // trying to access `a` as a shared borrow, so giving an error
} // &mut borrow of `a` ends here
我們在上篇文章說到,這段代碼:
println!("{:?}", a);
是過不了霸道的編譯器女王的檢查的?
為什么?
因為b借用了a的數據所有權,沒有還回來。
所以,這時,訪問a的數據時,編譯器女王報錯。
那要怎么辦?加大括號 {}。
如下 :
fn main() {
let mut a = vec![1, 2, 3];
{
let b = &mut a; // &mut borrow of `a` starts here
// any other code
} // &mut borrow of `a` ends here
println!("{:?}", a); // allow borrowing `a` as a shared borrow
}
我們可以看到,b 的“生命周期”,是限定在大括號 {}中的。
我們來看一個更清楚的代碼:
我們現在知道,可以用大括號來限定變量或引用的生命周期。但太多大括號,會讓你看得頭大。
沒關系,rust都為你考慮到了。下面是生命周期定義的標准寫法。
翠花,上代碼 :
// No inputs, return a reference
fn function<'a>() -> &'a str {}
// Single input
fn function<'a>(x: &'a str) {}
// Single input and output, both have the same lifetime
// The output should live at least as long as input exists
fn function<'a>(x: &'a str) -> &'a str {}
// Multiple inputs, only one input and the output share same lifetime
// The output should live at least as long as y exists
fn function<'a>(x: i32, y: &'a str) -> &'a str {}
// Multiple inputs, both inputs and the output share same lifetime
// The output should live at least as long as x and y exist
fn function<'a>(x: &'a str, y: &'a str) -> &'a str {}
// Multiple inputs, inputs can have different lifetimes 🔎
// The output should live at least as long as x exists
fn function<'a, 'b>(x: &'a str, y: &'b str) -> &'a str {}
我們可以看到,rust用'a 這樣的注解來標注“生命周期”,即:單引號字符+小寫字母。
如果有多個生命周期,就用字典順序,如:'a 'b 'c 'd,v如此類推。
那從上面 的代碼注釋,我們也很清楚的明白,如果定義是同一種生命周期的注解的變量或引用,它們應該是相同生命周期,用人類的話來說:命一樣長。
好理解。
上面的例子,是用在函數上,那其他類型呢?
我們來看看Struct 和Enum類型
請看下面代碼:
// Single element
// Data of x should live at least as long as Struct exists
struct Struct<'a> {
x: &'a str
}
// Multiple elements
// Data of x and y should live at least as long as Struct exists
struct Struct<'a> {
x: &'a str,
y: &'a str
}
// Variant with a single element
// Data of the variant should live at least as long as Enum exists
enum Enum<'a> {
Variant(&'a Type)
}
我們看到,struct中的變量,定義為同一生命周期注解'a,則它們的“命一樣長”。
也很好理解。
我們再看看接口實現和特征變量,如下 :
struct Struct<'a> {
x: &'a str
}
impl<'a> Struct<'a> {
fn function<'a>(&self) -> &'a str {
self.x
}
}
struct Struct<'a> {
x: &'a str,
y: &'a str
}
impl<'a> Struct<'a> {
fn new(x: &'a str, y: &'a str) -> Struct<'a> { // No need to specify <'a> after new; impl already has it
Struct {
x : x,
y : y
}
}
}
// 🔎
impl<'a> Trait<'a> for Type
impl<'a> Trait for Type<'a>
再看看泛型:
// 🔎
fn function<F>(f: F) where for<'a> F: FnOnce(&'a Type)
struct Struct<F> where for<'a> F: FnOnce(&'a Type) { x: F }
enum Enum<F> where for<'a> F: FnOnce(&'a Type) { Variant(F) }
impl<F> Struct<F> where for<'a> F: FnOnce(&'a Type) { fn x(&self) -> &F { &self.x } }
有同學說,如果每次寫函數定義,都要顯式定義生命周期注解。那不是很麻煩的一件事。
沒關系,rust再次為你安排上了。
針對函數類型fn:
1.參數全部都是傳遞引用的函數可以直接這樣定義:
..(x: &str, y: &str)
rust自動內部轉化為:
..<'a, 'b>(x: &'a str, y: &'b str)
2.參數部分傳遞引用的函數可以直接這樣定義:
..(x: i32, y: &str) -> &str
rust自動內部轉化為:
..<'a>(x: i32, y: &'a str) -> &'a str
3.多個參數,有部分參數是&self或&mut self的傳遞引用函數:
impl Impl{ fn function(&self, x: &str) -> &str {} }
rust自動內部轉化為:
impl<'a> Impl<'a>{ fn function(&'a self, x: &'b str) -> &'a str {} }
現在我們來看看靜態生命周期注解: 'static
其實,就是類似java中的靜態變量定義,它的生命周期是跟整個程序的生命周期一樣,它一般用來定義全局變量。
如下:
static N: i32 = 5; // A constant with 'static lifetime
let a = "Hello, world."; // a: &'static str
fn index() -> &'static str { // No need to mention <'static> ; fn index ̶<̶'̶s̶t̶a̶t̶i̶c̶>̶
"Hello, world!"
}
如果遇到什么問題,歡迎加入:rust新手群,在這里我可以提供一些簡單的幫助,加微信:360369487,注明:博客園+rust
這里簡單總結一下這幾個重要的概念:
1.在Rust,對數據或資源,Rust同一時間,只允許一個所有者。所有變量都是默認不可變的,數據一旦綁定到變量,這個變量就直接對這個數據擁有所有權(ownership),如果這個綁定變量,超出作用域(一般用大括號來限定),rustlang會自動釋放這個變量和數據占用的內存,這就是Rust能做到內存安全的核心原理。
2.如果,要再次綁定到另一個變量b,若數據是復制類型,數據會自動復制一份拷貝,再綁定到這個變量b上,所有權狀態置為“ copied ”。若是借用類型,這個數據的所有權暫時借用給這個變量b,所有權狀態置為“ moved ”。
3.資源(變量和數據)的生命周期,程序員自己控制,要保存資源的生命周期,在代碼中其他調用它的時候有效(alive)。直到用完,並顯示釋放資源。
其實Rust的設計哲學,就是:
內存安全
零成本抽象
實用性
也就是說,Rust 語言中所有語法特性都圍繞這三條哲學而設計,這也是 Rust 語言一致性的基礎。