Implementation of user data in cursive::Cursive

Implementation of user data in cursive::Cursive

(Jin Qing’s Column, Oct., 2022)

cursive::Cursive can store any user data:

pub struct Cursive {
    ...
    // User-provided data.
    user_data: Box<dyn Any>,
}

impl Cursive {
    ...
    
    pub fn set_user_data<T: Any>(&mut self, user_data: T) {
        self.user_data = Box::new(user_data);
    }

    pub fn user_data<T: Any>(&mut self) -> Option<&mut T> {
        self.user_data.downcast_mut()
    }

    pub fn take_user_data<T: Any>(&mut self) -> Option<T> {
        ...
    }

    pub fn with_user_data<F, T, R>(&mut self, f: F) -> Option<R>
    where
        F: FnOnce(&mut T) -> R,
        T: Any,
    {
        self.user_data().map(f)
    }

Example:

let mut siv = cursive_core::Cursive::new();

// Start with a simple `Vec<i32>` as user data.
siv.set_user_data(vec![1i32, 2, 3]);
assert_eq!(siv.user_data::<Vec<i32>>(), Some(&mut vec![1i32, 2, 3]));

// Let's mutate the data a bit.
siv.with_user_data(|numbers: &mut Vec<i32>| numbers.push(4));

// If mutable reference is not enough, we can take the data by value.
let data: Vec<i32> = siv.take_user_data().unwrap();
assert_eq!(data, vec![1i32, 2, 3, 4]);

// At this point the user data was removed and is no longer available.
assert_eq!(siv.user_data::<Vec<i32>>(), None);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值