Rust part16at TECH
Rust part16 - 暇つぶし2ch363:デフォルトの名無しさん
22/07/13 23:59:24.88 qlTJEO+a.net
>>353
もっと便利にできるぜ
use std::cell::Cell;
trait CellWithMethod<T> {
fn with<R>(&self, f: impl FnOnce(&mut T) -> R) -> R;
}
impl<T: Default> CellWithMethod<T> for Cell<T> {
#[inline]
fn with<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
let mut inner = self.take();
let result = f(&mut inner);
self.set(inner);
result
}
}
fn main() {
let foo = Cell::new(vec![1, 2, 3]);
foo.with(|v| v.push(7));
assert_eq!(4, foo.with(|v| v.len()));
assert_eq!(7, foo.with(|v| v[3]));
assert_eq!(vec![1, 2, 3, 7], foo.with(|v| v.clone()));
}


次ページ
続きを表示
1を表示
最新レス表示
レスジャンプ
類似スレ一覧
スレッドの検索
話題のニュース
おまかせリスト
オプション
しおりを挟む
スレッドに書込
スレッドの一覧
暇つぶし2ch