• 如何更加优雅和高效的管理Rust中的状态
  • 发布于 2个月前
  • 558 热度
    0 评论
  • 卧龙生
  • 1 粉丝 54 篇博客
  •   
在这篇文章中将分享一个在Rust中处理状态的奇妙技巧。这个小技巧将帮助你提升Rust技能,让你的代码更加优雅!

在Rust中,你可以为各种应用程序状态和相关数据定义一个枚举,如下所示:
// 堆代码 duidaima.com
enum CurrentState<'a, T> {
    Loading,
    Success(&'a T),
    Error(&'a str),
}
要创建一个为每个状态执行不同闭包的方法,定义一个trait,该方法以三个闭包作为参数:
trait DuringCurrentState<'a, T> {
    fn during_current_state(
        self,
        loading: impl FnOnce() + 'a,
        success: impl FnOnce(&T) + 'a,
        error: impl FnOnce(&str) + 'a,
    );
}

impl<'a, T> DuringCurrentState<'a, T> for CurrentState<'a, T> {
    fn during_current_state(
        self,
        loading: impl FnOnce() + 'a,
        success: impl FnOnce(&T) + 'a,
        error: impl FnOnce(&str) + 'a,
    ) {
        match self {
            CurrentState::Loading => loading(),
            CurrentState::Success(data) => success(data),
            CurrentState::Error(message) => error(message),
        }
    }
}
现在,你可以在CurrentState枚举实例上调用during_current_state方法,并为加载、成功和错误传递闭包:
fn main() {
    let success = String::from("State is success!");

    let state = CurrentState::Success(&success);

    state.during_current_state(
        || {
            println!("loading...");
        },
        | data | {
            println!("success: {:?}", data);
        },
        | message | {
            println!("error: {:?}", message);
        },
    );
}
现在可以在你的项目中尝试一下,这个方便的技巧将使Rust中的状态管理更加优雅和高效。

用户评论