// Copyright 2012 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. /// The `Deref` trait is used to specify the functionality of dereferencing /// operations, like `*v`. /// /// `Deref` also enables ['`Deref` coercions'][coercions]. /// /// [coercions]: ../../book/first-edition/deref-coercions.html /// /// # Examples /// /// A struct with a single field which is accessible via dereferencing the /// struct. /// /// ``` /// use std::ops::Deref; /// /// struct DerefExample { /// value: T /// } /// /// impl Deref for DerefExample { /// type Target = T; /// /// fn deref(&self) -> &T { /// &self.value /// } /// } /// /// fn main() { /// let x = DerefExample { value: 'a' }; /// assert_eq!('a', *x); /// } /// ``` #[lang = "deref"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Deref { /// The resulting type after dereferencing #[stable(feature = "rust1", since = "1.0.0")] type Target: ?Sized; /// The method called to dereference a value #[stable(feature = "rust1", since = "1.0.0")] fn deref(&self) -> &Self::Target; } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T: ?Sized> Deref for &'a T { type Target = T; fn deref(&self) -> &T { *self } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T: ?Sized> Deref for &'a mut T { type Target = T; fn deref(&self) -> &T { *self } } /// The `DerefMut` trait is used to specify the functionality of dereferencing /// mutably like `*v = 1;` /// /// `DerefMut` also enables ['`Deref` coercions'][coercions]. /// /// [coercions]: ../../book/first-edition/deref-coercions.html /// /// # Examples /// /// A struct with a single field which is modifiable via dereferencing the /// struct. /// /// ``` /// use std::ops::{Deref, DerefMut}; /// /// struct DerefMutExample { /// value: T /// } /// /// impl Deref for DerefMutExample { /// type Target = T; /// /// fn deref(&self) -> &T { /// &self.value /// } /// } /// /// impl DerefMut for DerefMutExample { /// fn deref_mut(&mut self) -> &mut T { /// &mut self.value /// } /// } /// /// fn main() { /// let mut x = DerefMutExample { value: 'a' }; /// *x = 'b'; /// assert_eq!('b', *x); /// } /// ``` #[lang = "deref_mut"] #[stable(feature = "rust1", since = "1.0.0")] pub trait DerefMut: Deref { /// The method called to mutably dereference a value #[stable(feature = "rust1", since = "1.0.0")] fn deref_mut(&mut self) -> &mut Self::Target; } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T: ?Sized> DerefMut for &'a mut T { fn deref_mut(&mut self) -> &mut T { *self } }