deferred_reference/reference.rs
1mod private {
2 pub trait Sealed {}
3 impl<T: ?Sized> Sealed for &T {}
4 impl<T: ?Sized> Sealed for &mut T {}
5}
6
7/// This trait is implemented for all references. Rust has only two types
8/// of references to a type `T: ?Sized`, namely `&T` and `&mut T`.
9/// This trait is sealed and can not be implemented for any other types.
10///
11/// # Example use
12/// This trait makes it possible to accept both immutable and mutable references
13/// as generic type parameters.
14/// ```
15/// use deferred_reference::Reference;
16/// use core::fmt::Debug;
17/// pub struct RefContainer<T>(T) where T: Reference;
18/// fn main() {
19/// let mut value = 42;
20/// let immutable_ref = RefContainer(&value); // takes an immutable...
21/// let mutable_ref = RefContainer(&mut value); // ... or mutable reference.
22/// //let owned = RefContainer(value); // not a reference, so not allowed
23///
24/// // this also works for references to trait objects:
25/// fn dyn_ref(reference: &dyn Debug) -> RefContainer<&dyn Debug> {
26/// RefContainer(reference)
27/// }
28/// let dyn_ref: RefContainer<&dyn Debug> = dyn_ref(&value);
29/// }
30/// ```
31pub trait Reference: private::Sealed {
32 /// The type that the reference points to.
33 type Target: ?Sized;
34}
35impl<T: ?Sized> Reference for &T {
36 type Target = T;
37}
38impl<T: ?Sized> Reference for &mut T {
39 type Target = T;
40}