Rust 1.39.0 已經發布。此版本的亮點包括 async/.await,對 match 守衛 by-move 綁定的共享引用,以及函數參數的屬性。
async/.await 穩定
此版本 async/.await 特性已經穩定,這意味著現在可以定義 async 函數和塊,並進行 .await 操作。
async 函數通過 async fn 引入,被調用時會返回一個 Future,該 Future 是一個會掛起的計算,可以使用 .await 運行並完成計算。而除了 async fn,async{...} 和 async move{...} 塊也可以用來定義「非同步文字」,它們的行為像閉包。
match 守衛引用 by-move 綁定
在 Rust 中進行模式匹配時,一個變數,也就是「綁定」,可以通過以下方式界定:
不可更改或可變地 by-reference。這可以通過諸如ref my_var
或ref mut my_var
分別明確地實現,在大多數情況下,綁定模式將自動推導。
by-value,或者當綁定變數的類型實現 Copy 時 by-copy,否則 by-move。
以往,Rust 將禁止在表達式的保護結構中共享對 match 表達式中 if 守衛的 by-move 綁定的引用,這意味著以下代碼將被拒絕:
fn main() { let array: Box<[u8; 4]> = Box::new([1, 2, 3, 4]); match array { nums // ---- `nums` is bound by move. if nums.iter().sum::<u8>() == 10 // ^------ `.iter()` implicitly takes a reference to `nums`. => { drop(nums); // ----------- `nums` was bound by move and so we have ownership. } _ => unreachable!(), }
}
Rust 1.39 中,上面的代碼段現在已被編譯器接受,此特性可以為整體的 match 表達式帶來更流暢、更一致的體驗。
函數參數的屬性
現在允許在函數、閉包和函數指針的參數上使用屬性。
比如以往這樣編寫:
#[cfg(windows)]
fn len(slice: &[u16]) -> usize {
slice.len()
}
#[cfg(not(windows))]
fn len(slice: &[u8]) -> usize {
slice.len()
}
現在可以以更簡潔的方式:
fn len(
#[cfg(windows)] slice: &[u16], // This parameter is used on Windows.
#[cfg(not(windows))] slice: &[u8], // Elsewhere, this one is used.
) -> usize {
slice.len()
}
這裡可以使用的屬性包括:
條件編譯:cfg 和 cfg_attr
控制 lint:allow、warn、deny 與 forbid
應用於項目的過程宏屬性使用的幫助程序屬性
這在整個語言生態中提供了一個更具可讀性的基於宏的 DSL。
標準庫中增加的 const fn
此版本中,以下函數成為 const fn:
增加到標準庫的函數
以下函數已經穩定:
詳情查看更新說明:
[admin
]