Implementation of user data in cursive::Cursive

Posted 金庆

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);

以上是关于Implementation of user data in cursive::Cursive的主要内容,如果未能解决你的问题,请参考以下文章

Implementation of user data in cursive::Cursive

the-implementation-of-epoll

Implementation of Message Receiver

dataStructure@ Implementation of minimal heap

An implementation of this using bufferedReader:

trickA variant of token bucket implementation