..

Rust Fn 的实践


截取部分 jlib-rs 中的代码。

type FnOnceType = Result<ServerInfoResponse, serde_json::error::Error>;

pub fn request<F> (config: Config, op: F)
    where F: Fn(FnOnceType) {

    //some operations

    op(data)
}

这是用来获取 serverInfoAPI, 把请求到的数据通过 op 回调的方式返回给调用方, 这里对 op 进行了限定, trait Fn
还有 FnOnce, FnMut。如果此处 op 替换一下其他的 trait , 则修改如下:

// FnOnce
pub fn request<F> (config: Config, op: F)
    where F: FnOnce(FnOnceType) {

// FnMut
pub fn request<F> (config: Config, mut op: F)
    where F: FnMut(FnOnceType) {

看官网的介绍, 这三个关系如下:

-------FnOnce (supertrait)
-----/         \
----/           \
--Fn(subtraits)  FnMut(subtraits)

FnOnce (self) are functions that can be called once1
FnMut (&mut self) are functions that can be called if they have &mut access to their environment2
Fn (&self) are functions that can be called if they only have & access to their environment3



  1. FnOnce

  2. FnMut

  3. Fn