金庆的专栏

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  423 随笔 :: 0 文章 :: 454 评论 :: 0 Trackbacks

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);
posted on 2022-10-02 16:38 金庆 阅读(99) 评论(0)  编辑 收藏 引用 所属分类: 8. Rust

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理