自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Fn FnMut FnOnce 傻傻分不清

開發(fā) 前端
同時閉包引用變量也是有優(yōu)先級的:優(yōu)先只讀借用,然后可變借用,最后轉(zhuǎn)移所有權(quán)。本篇文章看下,如何將閉包當(dāng)成參數(shù)或返回值。

[[415256]]

本文轉(zhuǎn)載自微信公眾號「董澤潤的技術(shù)筆記」,作者董澤潤。轉(zhuǎn)載本文請聯(lián)系董澤潤的技術(shù)筆記公眾號。

同時閉包引用變量也是有優(yōu)先級的:優(yōu)先只讀借用,然后可變借用,最后轉(zhuǎn)移所有權(quán)。本篇文章看下,如何將閉包當(dāng)成參數(shù)或返回值

Go 閉包調(diào)用

  1. package main 
  2.  
  3. import "fmt" 
  4.  
  5. func test(f func()) { 
  6.     f() 
  7.     f() 
  8.  
  9. func main() { 
  10.     a:=1 
  11.     fn := func() { 
  12.         a++ 
  13.         fmt.Printf("a is %d\n", a) 
  14.     } 
  15.     test(fn) 

上面是 go 的閉包調(diào)用,我們把 fn 當(dāng)成參數(shù),傳給函數(shù) test. 閉包捕獲變量 a, 做自增操作,同時函數(shù) fn 可以調(diào)用多次

對于熟悉 go 的人來說,這是非常自然的,但是換成 rust 就有問題了

  1. fn main() { 
  2.     let s = String::from("wocao"); 
  3.     let f = || {println!("{}", s);}; 
  4.     f(); 

比如上面這段 rust 代碼,我如果想把閉包 f 當(dāng)成參數(shù)該怎么寫呢?上周分享的閉包我們知道,閉包是匿名的

  1. c = hello_cargo::main::closure-2 (0x7fffffffe0e0, 0x7fffffffe0e4) 
  2. b = hello_cargo::main::closure-1 (0x7fffffffe0e0) 
  3. a = hello_cargo::main::closure-0 

在運行時,類似于上面的結(jié)構(gòu)體,閉包結(jié)構(gòu)體命名規(guī)則 closure-xxx, 同時我們是不知道函數(shù)簽名的

引出 Trait

官方文檔 給出了方案,標(biāo)準(zhǔn)庫提供了幾個內(nèi)置的 trait, 一個閉包一定實現(xiàn)了 Fn, FnMut, FnOnce 其中一個,然后我們可以用泛型 + trait 的方式調(diào)用閉包

  1. $ cat src/main.rs 
  2. fn test<T>(f: T) where 
  3.     T: Fn() 
  4.     f(); 
  5.  
  6. fn main() { 
  7.     let s = String::from("董澤潤的技術(shù)筆記"); 
  8.     let f = || {println!("{}", s);}; 
  9.     test(f); 
  10.  
  11. $ cargo run 
  12.     Finished dev [unoptimized + debuginfo] target(s) in 0.00s 
  13.      Running `target/debug/hello_cargo` 
  14. 董澤潤的技術(shù)筆記 

上面將閉包 f 以泛型參數(shù)的形式傳給了函數(shù) test, 因為閉包實現(xiàn)了 Fn trait. 剛學(xué)這塊的人可能會糊涂,其實可以理解類比 go interface, 但本質(zhì)還是不一樣的

  1. let f = || {s.push_str("不錯");}; 

假如 test 聲明不變,我們的閉包修改了捕獲的變量呢?

  1. |     let f = || {s.push_str("不錯");}; 
  2. |             ^^  - closure is `FnMut` because it mutates the variable `s` here 
  3. |             | 
  4. |             this closure implements `FnMut`, not `Fn` 
  5. |     test(f); 

報錯說 closure 實現(xiàn)的 trait 是 FnMut, 而不是 Fn

  1. fn test<T>(mut f: T) where 
  2.     T: FnMut() 
  3.     f(); 
  4.  
  5. fn main() { 
  6.     let mut s = String::from("董澤潤的技術(shù)筆記"); 
  7.     let f = || {s.push_str("不錯");}; 
  8.     test(f); 

上面是可變借用的場景,我們再看一下 move 所有權(quán)的情況

  1. fn test<T>(f: T) where 
  2.     T: FnOnce() 
  3.     f(); 
  4.  
  5. fn main() { 
  6.     let s = String::from("董澤潤的技術(shù)筆記"); 
  7.     let f = || {let _ = s;}; 
  8.     test(f); 

上面我們把自由變量 s 的所有權(quán) move 到了閉包里,此時 T 泛型的特征變成了 FnOnce, 表示只能執(zhí)行一次。那如果 test 調(diào)用閉包兩次呢?

  1. 1 | fn test<T>(f: T) where 
  2.   |            - move occurs because `f` has type `T`, which does not implement the `Copy` trait 
  3. ... 
  4. 4 |     f(); 
  5.   |     --- `f` moved due to this call 
  6. 5 |     f(); 
  7.   |     ^ value used here after move 
  8.   | 
  9. note: this value implements `FnOnce`, which causes it to be moved when called 
  10.  --> src/main.rs:4:5 
  11.   | 
  12. 4 |     f(); 

編譯器提示第一次調(diào)用的時候,己經(jīng) move 了,再次調(diào)用無法訪問。很明顯此時自由變量己經(jīng)被析構(gòu)了 let _ = s; 離開詞法作用域就釋放了,rust 為了內(nèi)存安全當(dāng)然不允許繼續(xù)訪問

  1. fn test<T>(f: T) where 
  2.     T: Fn() 
  3.     f(); 
  4.     f(); 
  5.  
  6. fn main() { 
  7.     let s = String::from("董澤潤的技術(shù)筆記"); 
  8.     let f = move || {println!("s is {}", s);}; 
  9.     test(f); 
  10.     //println!("{}", s); 

那么上面的代碼例子, 是否可以運行呢?當(dāng)然啦,此時變量 s 的所有權(quán) move 給了閉包 f, 生命周期同閉包,反復(fù)調(diào)用也沒有副作用

深入理解

本質(zhì)上 Rust 為了內(nèi)存安全,才引入這么麻煩的處理。平時寫 go 程序,誰會在乎對象是何時釋放,對象是否存在讀寫沖突呢?總得有人來做這個事情,Rust 選擇在編譯期做檢查

  • FnOnce consumes the variables it captures from its enclosing scope, known as the closure’s environment. To consume the captured variables, the closure must take ownership of these variables and move them into the closure when it is defined. The Once part of the name represents the fact that the closure can’t take ownership of the same variables more than once, so it can be called only once.
  • FnMut can change the environment because it mutably borrows values.
  • Fn borrows values from the environment immutably.

上面來自官網(wǎng)的解釋,F(xiàn)n 代表不可變借用的閉包,可重復(fù)執(zhí)行,F(xiàn)nMut 代表閉包可變引用修改了變量,可重復(fù)執(zhí)行 FnOnce 代表轉(zhuǎn)移了所有權(quán),同時只能執(zhí)行一次,再執(zhí)行的話自由變量脫離作用域回收了

  1. # mod foo { 
  2. pub trait Fn<Args> : FnMut<Args> { 
  3.     extern "rust-call" fn call(&self, args: Args) -> Self::Output
  4.  
  5. pub trait FnMut<Args> : FnOnce<Args> { 
  6.     extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output
  7.  
  8. pub trait FnOnce<Args> { 
  9.     type Output
  10.  
  11.     extern "rust-call" fn call_once(self, args: Args) -> Self::Output
  12. # } 

上面是標(biāo)準(zhǔn)庫中,F(xiàn)n, FnMut, FnOnce 的實現(xiàn)。可以看到 Fn 繼承自 FnMut, FnMut 繼承自 FnOnce

  1. Fn(u32) -> u32 

前文例子都是無參數(shù)的,其實還可以帶上參數(shù)

由于 Fn 是繼承自 FnMut, 那么我們把實現(xiàn) Fn 的閉包傳給 FnMut 的泛型可以嘛?

  1. $ cat src/main.rs 
  2. fn test<T>(mut f: T) where 
  3.     T: FnMut() 
  4.     f(); 
  5.     f(); 
  6.  
  7. fn main() { 
  8.     let s = String::from("董澤潤的技術(shù)筆記"); 
  9.     let f = || {println!("s is {}", s);}; 
  10.     test(f); 
  1. $ cargo run 
  2.    Compiling hello_cargo v0.1.0 (/Users/zerun.dong/code/rusttest/hello_cargo) 
  3.     Finished dev [unoptimized + debuginfo] target(s) in 1.47s 
  4.      Running `target/debug/hello_cargo` 
  5. is 董澤潤的技術(shù)筆記 
  6. is 董澤潤的技術(shù)筆記 

當(dāng)然可以看起來沒有問題,F(xiàn)nMut 告訴函數(shù) test 這是一個會修改變量的閉包,那么傳進來的閉包不修改當(dāng)然也沒問題

上圖比較出名,由于有繼承關(guān)系,實現(xiàn) Fn 可用于 FnMut 和 FnOnce 參數(shù),實現(xiàn) FnMut 可用于 FnOnce 參數(shù)

函數(shù)指針

  1. fn call(f: fn()) {    // function pointer 
  2.     f(); 
  3.  
  4. fn main() { 
  5.     let a = 1; 
  6.  
  7.     let f = || println!("abc");     // anonymous function 
  8.     let c = || println!("{}", &a);  // closure 
  9.  
  10.     call(f); 
  11.     call(c); 

函數(shù)和閉包是不同的,上面的例子中 f 是一個匿名函數(shù),而 c 引用了自由變量,所以是閉包。這段代碼是不能執(zhí)行的

  1. 9  |     let c = || println!("{}", &a);  // closure 
  2.    |             --------------------- the found closure 
  3. ... 
  4. 12 |     call(c); 
  5.    |          ^ expected fn pointer, found closure 

編譯器告訴我們,12 行要求參數(shù)是函數(shù)指針,不應(yīng)該是閉包

閉包作為返回值

參考 impl Trait 輕松返回復(fù)雜的類型,impl Trait 是指定實現(xiàn)特定特征的未命名但有具體類型的新方法。你可以把它放在兩個地方:參數(shù)位置和返回位置

  1. fn returns_closure() -> Box<dyn Fn(i32) -> i32> { 
  2.     Box::new(|x| x + 1) 
  3.  
  4. fn main() { 
  5.     let f = returns_closure(); 
  6.     println!("res is {}", f(11)); 

在以前,從函數(shù)處返回閉包的唯一方法是,使用 trait 對象,大家可以試試不用 Box 裝箱的報錯提示

  1. fn returns_closure() -> impl Fn(i32) -> i32 { 
  2.     |x| x + 1 
  3.  
  4. fn main() { 
  5.     let f = returns_closure(); 
  6.     println!("res is {}", f(11)); 

現(xiàn)在我們可以用 impl 來實現(xiàn)閉包的返回值聲明

  1. fn test() -> impl FnMut(char) { 
  2.     let mut s = String::from("董澤潤的技術(shù)筆記"); 
  3.     |c| { s.push(c); } 
  4.  
  5. fn main() { 
  6.     let mut c = test(); 
  7.     c('d'); 
  8.     c('e'); 

來看一個和引用生命周期相關(guān)的例子,上面的代碼返回閉包 c, 對字符串 s 進行追回作。代碼執(zhí)行肯定報錯:

  1.  --> src/main.rs:3:5 
  2.   | 
  3. 3 |     |c| { s.push(c); } 
  4.   |     ^^^   - `s` is borrowed here 
  5.   |     | 
  6.   |     may outlive borrowed value `s` 
  7.   | 
  8. note: closure is returned here 
  9.  --> src/main.rs:1:14 
  10.   | 
  11. 1 | fn test() -> impl FnMut(char) { 
  12.   |              ^^^^^^^^^^^^^^^^ 
  13. help: to force the closure to take ownership of `s` (and any other referenced variables), use the `move` keyword 
  14.   | 
  15. 3 |     move |c| { s.push(c); } 
  16.   |     ^^^^^^^^ 

提示的很明顯,變量 s 脫離作用域就釋放了,編譯器也提示我們要 move 所有權(quán)給閉包,感興趣的自己修改測試一下

 

責(zé)任編輯:武曉燕 來源: 董澤潤的技術(shù)筆記
相關(guān)推薦

2022-05-05 13:54:37

SPI機制APISPI

2021-03-10 08:56:37

Zookeeper

2021-01-22 08:37:02

二進制Binary SemaReentrant L

2021-03-23 10:45:23

CookieSession前端

2021-05-09 21:57:08

數(shù)據(jù)倉庫Olap

2021-10-06 23:31:45

HibernateJPASpring Data

2024-02-29 09:08:56

Encoding算法加密

2021-08-02 12:50:45

sessiontokenJava

2021-07-27 07:31:16

JavaArrayList數(shù)組

2022-05-15 21:52:04

typeTypeScriptinterface

2018-12-17 12:30:05

Kubernetes存儲存儲卷

2019-06-18 09:45:19

正向代理反向代理IT

2020-10-30 08:20:04

SD卡TF卡存儲

2022-04-15 11:47:47

LVSNginx負(fù)載均衡

2023-09-03 21:18:07

Python編程語言

2018-05-22 16:24:20

HashMapJavaJDK

2020-03-03 17:35:09

Full GCMinor

2015-02-28 10:01:00

云計算IT架構(gòu)虛擬化

2023-02-27 15:46:19

數(shù)據(jù)元元數(shù)據(jù)

2022-02-25 09:14:33

類變量共享實例變量
點贊
收藏

51CTO技術(shù)棧公眾號