// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::ops::{Deref, DerefMut}; struct CheckedDeref { value: T, check: F } impl bool, T> Deref for CheckedDeref { type Target = T; fn deref(&self) -> &T { assert!((self.check)(&self.value)); &self.value } } impl bool, T> DerefMut for CheckedDeref { fn deref_mut(&mut self) -> &mut T { assert!((self.check)(&self.value)); &mut self.value } } fn main() { let mut v = CheckedDeref { value: vec![0], check: |v: &Vec<_>| !v.is_empty() }; v.push(1); assert_eq!(*v, vec![0, 1]); }