歡迎您光臨本站 註冊首頁

Rust 1.39.0 發布,async/.await 終於穩定了

←手機掃碼閱讀     admin @ 2019-11-11 , reply:0

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_varref 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()
}

這裡可以使用的屬性包括:

  1. 條件編譯:cfg 和 cfg_attr

  2. 控制 lint:allow、warn、deny 與 forbid

  3. 應用於項目的過程宏屬性使用的幫助程序屬性

這在整個語言生態中提供了一個更具可讀性的基於宏的 DSL。

標準庫中增加的 const fn

此版本中,以下函數成為 const fn:

  • Vec::new、String::new 與 LinkedList::new
  • str::len、[T]::len 與 str::as_bytes
  • abs、wrapping_abs 與 overflowing_abs

增加到標準庫的函數

以下函數已經穩定:

  • Pin::into_inner
  • Instant::checked_duration_since 與 Instant::saturating_duration_since

詳情查看更新說明:

https://blog.rust-lang.org/2019/11/07/Rust-1.39.0.html


[admin ]

來源:OsChina
連結:https://www.oschina.net/news/111214/rust-1-39-0-released
Rust 1.39.0 發布,async/.await 終於穩定了已經有140次圍觀

http://coctec.com/news/all/show-post-219169.html